Created
September 24, 2017 20:04
-
-
Save jalopezsuarez/30a1f82920270378375794a13be6721b to your computer and use it in GitHub Desktop.
Underlined UITextView in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// UnderlinedTextField.swift | |
// Assembly | |
// | |
// Created by Jose Antonio Lopez (jalopezsuarez@gmail.com) on 01/01/17. | |
// Copyright (c) 2017 Vemovi Desarrolla sl. All rights reserved. | |
// | |
import Foundation | |
@IBDesignable | |
class UnderlinedTextField : UITextField, UITextFieldDelegate { | |
@IBInspectable var hintTextColor : UIColor? | |
@IBOutlet weak var nextField : UITextField? | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
self.delegate = self | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
self.delegate = self | |
} | |
override func draw(_ rect: CGRect) { | |
super.draw(rect) | |
let lineLayer = CALayer() | |
lineLayer.frame = CGRect(x: 0, y: rect.size.height-1, width: rect.size.width, height: 1) | |
lineLayer.backgroundColor = UIColor.white.cgColor | |
layer.addSublayer(lineLayer) | |
} | |
override func drawPlaceholder(in rect: CGRect) { | |
let color = (hintTextColor ?? textColor)! | |
let placeholderAttr : [NSAttributedStringKey : AnyObject] = [NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue): color, NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue) : font!] | |
let placeholderTextSize = placeholder!.size(withAttributes: placeholderAttr) | |
let placeholderRect = CGRect(x: 0, y: abs(rect.size.height - placeholderTextSize.height) / 2, width: placeholderTextSize.width, height: placeholderTextSize.height) | |
NSString(string: placeholder!).draw(in: placeholderRect, withAttributes: placeholderAttr) | |
} | |
func textFieldShouldReturn(_ textField: UITextField) -> Bool { | |
if nextField != nil { | |
nextField!.becomeFirstResponder() | |
} else { | |
resignFirstResponder() | |
} | |
return false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment