Bright Future Bright Future - 2 months ago 8
iOS Question

How to customize UITextField?

I'm following this answer to create a custom UITextField, however, I couldn't get the same result, here's how I did it:

Method 1 (exactly like the original answer):

extension UITextField {

func useUnderLine() {
let border = CALayer()
let borderWidth = CGFloat(1.0)
border.borderColor = UIColor.white.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - borderWidth, width: self.frame.size.width, height: self.frame.size.height)
border.borderWidth = borderWidth
self.layer.addSublayer(border)
self.layer.masksToBounds = true
}
}

override func viewDidLoad() {
super.viewDidLoad()

firstTextField.useUnderLine()
}


Method 2 (using a custom class):

class CustomTextField: UITextField {

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)

let borderWidth = CGFloat(1.0)
self.layer.borderColor = UIColor.white.cgColor
self.layer.frame = CGRect(x: 0, y: self.frame.size.height - borderWidth, width: self.frame.size.width, height: self.frame.size.height)
self.layer.borderWidth = borderWidth
self.backgroundColor = UIColor.black
self.layer.masksToBounds = true
}
}


Both methods failed to work, however, I got different results for them:



first text field uses method 1, the other 3 use method 2


I want a textfield with only the bottom line, how do I get that?


Edit (here's how outlets are set):

@IBOutlet weak var firstTextField: UITextField!
@IBOutlet weak var secondTextField: CustomTextField! { didSet { secondTextField.delegate = self } }
@IBOutlet weak var thirdTextField: CustomTextField! { didSet { thirdTextField.delegate = self } }
@IBOutlet weak var fourthTextField: CustomTextField! { didSet { fourthTextField.delegate = self } }

Answer

If you´re using the Storyboard to create your textField use the following:

firstTextField.borderStyle = .none
firstTextField.layoutIfNeeded()

let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = UIColor.darkGray.cgColor

print(firstTextField.frame)
border.frame = CGRect(x: 0, y: firstTextField.frame.size.height - width, width:  firstTextField.frame.size.width, height: firstTextField.frame.size.height)
border.borderWidth = width

firstTextField.layer.addSublayer(border)
firstTextField.layer.masksToBounds = true

If you´re creating your textField programmatically use the following:

let textField = UITextField(frame: CGRect(x: 0, y: 20, width: 100, height: 20))

let border = CALayer()
let width = CGFloat(2.0)
border.borderColor = UIColor.darkGray.cgColor
border.frame = CGRect(x: 0, y: textField.frame.size.height - width, width:  textField.frame.size.width, height: textField.frame.size.height)

border.borderWidth = width
textField.borderStyle = .none
textField.layer.addSublayer(border)
textField.layer.masksToBounds = true

self.view.addSubview(textField)

Will give you:
enter image description here