0

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)
}
Rakesha Shastri
  • 11,053
  • 3
  • 37
  • 50
dinggu
  • 111
  • 7

2 Answers2

1

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
    }

}
Rakesha Shastri
  • 11,053
  • 3
  • 37
  • 50
1
   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
  }
Kathiresan Murugan
  • 2,783
  • 3
  • 23
  • 44