[英]How to display alert when the value of textfield is 0 in swift4?
I want to display an alert when the value of textfield is 0. However, putting a value of 0 in the textfield does not show the alert. 我想在textfield的值为0时显示警报。但是,在textfield中输入0的值不会显示警报。
How can I solve the problem? 我该如何解决这个问题?
@IBOutlet var priceTextfield: UITextField!
if Int(priceTextfield.text!) == 0 {
let aert = UIAlertController(title: "OK", message: "Price must be greater than 0.", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default)
alert.addAction(OK)
self.present(alert, animated: false)
}
You should handle this is textFieldShouldEndEditing
delegate. 您应该处理的是
textFieldShouldEndEditing
委托。
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
if Double(textField.text!) == 0 {
// Show alert
return false
}
return true
}
Note: Your view controller needs to conform to the UITextFieldDelegate
and the text field delegate has to be set. 注意:您的视图控制器需要符合
UITextFieldDelegate
并且必须设置文本字段委托。
class YourViewController: UIViewController, UITextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
priceTextfield.delegate = self
}
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
if textField.text.count > 1 {
if let value = Int(textField.text), value == 0 { // Convert string to Int
// Show alert
}
}
return true
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.