Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Underlined UITextView in Swift
//
// 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