最佳答案
旁注:您可以使用外部库来完成我将向您展示的内容。但是,我相信对于刚接触 Swift 的人来说,这段代码可以提供一些关于正确使用该语言进行移动开发的见解。此外,过度使用外部库通常不是一个好习惯,因为当添加更多依赖项时,项目的大小会增加,从而使编译速度变慢并占用设备上的更多内存。只要有可能,您就应该使用 Swift 的标准库和内置功能。</p>
好的,所以我们必须首先设置一条错误消息。这可以通过创建一个新的 UILabel
轻松完成。我不知道您是否使用 Storyboard来创建您的 UI 元素,但在下面的代码中,我假设您以编程方式创建了所有内容。
注意我是如何添加一个target到submitButton
来改变textField
和errorMessage
的如果不满足特定条件(在本例中,如果 textField
为空)。
此外,请注意我如何使用 UITextFieldDelegate
的方法 didBeginEditing(...)
重置 textField
的边框颜色并隐藏errorMessage
再次出现。
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
}
}
关于ios - 如何在 Swift 的 UITextField 下显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53102181/