Condition on TextField in Alarm message

Hi everyone

I'm trying to make two conditions on a textfield that I have put on an alarm message.

First condition is that the OK button is disabled till a value is entered on the textfield. (this is fixed, I do like a counter of characters in the textfield)

Second condition es that the OK button still disabled if the user enter the value 0.


I don't know how to make this. The button must enable when the value entered on textfield is > 0.


Here is the code for first condition:


ok.isEnabled = false
          
alertMessage.addAction(ok)
           
 alertMessage.addTextField { (textField) -> Void in
                amountTextField = textField
                amountTextField?.placeholder = "Introduzca un valor"
                amountTextField?.keyboardType = UIKeyboardType.numberPad
                
let toolBar = UIToolbar()
                toolBar.sizeToFit()
               
 let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(self.doneClicked))
                toolBar.setItems([doneButton], animated: false)
                amountTextField?.inputAccessoryView = toolBar
              
  NotificationCenter.default.addObserver(forName: .UITextFieldTextDidChange, object: textField, queue: OperationQueue.main, using: {_ in

                    let textCount = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines).characters.count ?? 0
                    let textIsNotEmpty = textCount > 0
                    ok.isEnabled = textIsNotEmpty
                })
            }
            self.present(alertMessage, animated: true, completion: nil)

Thanks for any help.

Accepted Answer

Does this compile and execute well ? If your code presently works, just complete this part as follows:


                    let trimmedText = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines)
                    let textCount = trimmedText.characters.count ?? 0
                    let textIsNotEmpty = textCount > 0
                    var textIsPositiveNumber = false     // Not positive or not a value
                    if let textValue = Int(trimmedText) {     // So, it is a number
                         textIsPositiveNumber = textValue > 0
                    }
                    ok.isEnabled = textIsNotEmpty && textIsPositiveNumber

My code worked, but with your code now I get exactly what I expected for.

thank you once more.

Condition on TextField in Alarm message
 
 
Q