Reputation: 49
How can I change the border of my uitextfield when it's selected or start to type some text in it
i try but it don't work check code
@IBOutlet weak var email: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var userName: UITextField!
whats wrong here no error but nothing happens
func fieldLayout () {
if (self.password.isSelected == true) {
self.password.layer.borderWidth = 4
self.password.layer.borderColor = #colorLiteral(red: 0, green: 0.8362106681, blue: 1, alpha: 1)
}
if (self.email.isSelected == true) {
self.email.layer.borderWidth = 5
self.email.layer.borderColor = #colorLiteral(red: 0, green: 0.8362106681, blue: 1, alpha: 1)
}
if (self.userName.isSelected == true) {
self.userName.layer.borderWidth = 5
self.userName.layer.borderColor = #colorLiteral(red: 0, green: 0.8362106681, blue: 1, alpha: 1)
}
}
Upvotes: 1
Views: 9007
Reputation: 11210
If you want to highlight TextField when user starts typing, I suggest you to use UITextField
delegate method textFieldDidBeginEditing
for handling when user starts typing.
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField == email {
textField.layer.borderWidth = 4
textField.layer.borderColor = // your color
} else if ...
}
you can also use textFieldDidEndEditing
delegate method for handling when user is done with typing
func textFieldDidEndEditing(_ textField: UITextField) {
textField.layer.borderWidth = // default width
textField.layer.borderColor = // default color
}
So if you want to use these methods, don't forget to set delegate
properties of your TextFields in viewDidLoad
for example
email.delegate = self
password.delegate = self
userName.delegate = self
also don't forget to implement UITextFieldDelegate
protocol
class ViewController: UIViewController, UITextFieldDelegate
Upvotes: 7
Reputation: 1527
You can do like this:
func textFieldDidBeginEditing(_ textField: UITextField) {
// textField.borderStyle = .line
textField.layer.borderColor = UIColor.red.cgColor //your color
textField.layer.borderWidth = 2.0
}
func textFieldDidEndEditing(_ textField: UITextField) {
textField.layer.borderWidth = 0.0
}
You can check the textField tag and set the color accordingly.
Upvotes: 1