I am trying to create an underlined text field with placeholder text, I got the following extension to help out.
extension UITextField {
func setBottomLine(borderColor: UIColor) {
borderStyle = .none
backgroundColor = .clear
let borderLine = CALayer()
borderLine.frame = CGRect(x: 0, y: frame.height - 2, width: frame.width, height: 2)
layer.addSublayer(borderLine)
}
I call this extension in layout subviews of my view controller, and whenever I assign placeholder text nothing shows up. I am very confused on what the problem is. Thanks!
CodePudding user response:
extension UITextField {
func setUnderLine() {
let border = CALayer()
let width = CGFloat(0.5)
border.borderColor = UIColor.darkGray.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width - 10, height: self.frame.size.height)
border.borderWidth = width
self.layer.addSublayer(border)
self.layer.masksToBounds = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
mytextField.setUnderLine()
}
CodePudding user response:
Check this out.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var yourTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
yourTextField.textFieldUnderscoreAndPlaceholder()
}
}
extension UITextField {
//MARK: Text underscore with placeholder
func textFieldUnderscoreAndPlaceholder() {
//Underscore
let textFieldUnderscore = CALayer()
textFieldUnderscore.frame = CGRect(x: 0.0, y: frame.height - 1, width: frame.width, height: 1.0)
bounds = bounds.insetBy(dx: 0, dy: -2)
textFieldUnderscore.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1).cgColor
layer.addSublayer(textFieldUnderscore)
//Placeholder
placeholder = "Type some text here..."
}
}