Reputation:
I want to show the error under an UItextfield and the border's color of the textfield turn into red.
How to do this? Thanks so much
Upvotes: 1
Views: 9570
Reputation: 905
Side Note: You could use external libraries to do what I am about to show you. However, I believe that for someone new to Swift, this code can provide some insights on proper use of the language for mobile development. Also, excessive use of external libraries is often not good practice because your project will increase in size when more dependencies are added, making it slower to compile and take up more memory on the device. Whenever you can, you should use Swift's standard libraries and built-in functionality.
Ok, so we're going to have to setup an error message, first. This is easily done by creating a new UILabel
. I don't know if you used storyboards to create your UI elements, but in the code below I just assume that you created everything programmatically.
Pay attention to how I add a target to submitButton
to change textField
's and errorMessage
's appearance if a certain condition is not met (in this case, if textField
is empty).
Also, notice how I use UITextFieldDelegate
's method didBeginEditing(...)
to reset the textField
's border colour and hide errorMessage
again.
class viewController: UIViewController, UITextFieldDelegate {
private let textField = UITextField()
private let errorMessage = UILabel()
private let submitButton = UIButton()
override viewDidLoad() {
super.viewDidLoad()
/* setup your UI elements here */
setupTextField()
setupErrorMessage()
setupSubmitButton()
}
func setupTextField() {
/* setup your text field here (you did this already) */
}
func setupErrorMessage() {
/* Here, I am using AutoLayout to lay out the errorMessage on the screen.
If you used storyboard, delete every line in this function except where
we set the message to hidden */
errorMessage.translatesAutoResizingMaskIntoConstraints = false
errorMessage.text = "Error Message"
errorMessage.textColor = .red
errorMessage.isHidden = true
self.addSubView(errorMessage)
NSLayoutConstraints.activate([
textField.leadingAnchor.constraint(equalTo: textField.leadingAnchor),
textField.topAnchor.constraint(equalTo: textField.bottomAnchor, constant: 10.0)
])
}
func setupSubmitButton() {
/* setup your submit button here (you did this already) */
submitButton.addTarget(self, action: #selector(submitButtonPressed(_ :)), for: .touchUpInside)
}
@objc func submitButtonPressed() {
if textField.text.isEmpty {
errorMessage.isHidden = false
textField.layer.borderColor = .red
}
}
/* use a UITextFieldDelegate method to change the textField's border color
to blue again after the user has corrected the mistake
(for example, after the user starts typing into the textField again) */
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.layer.borderColor = .blue
errorMessage.isHidden = true
}
}
Upvotes: 3