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.
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.
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.
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.