Search code examples
iosswiftuitextfielddelegate

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.

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)
}

Solution

  • 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
        }
    
    }