HMasood HMasood - 1 year ago 82
Swift Question

Button not enabling/disabling when textfield has integer in it

I am trying to activate a "convert" button once a user has inputted an integer value into a textfield labeled "Fahrenheit." I am having trouble gettting the text field to activate once integers are typed in the text field. Please see my code below for reference

override func viewDidLoad() {
Convert.enabled = false
Fahrenheit.delegate = self
Fahrenheit.keyboardType = .DecimalPad

if Int(Fahrenheit.text!) != nil{
Convert.enabled = true
Convert.enabled = false


Answer Source

You can implement textField(textField:shouldChangeCharactersInRange:replacementString:) from UITextFieldDelegate protocol and check if textField contains any text:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
  let currentText = NSString(string: textField.text ?? "")
  let newText = currentText.stringByReplacingCharactersInRange(range, withString: string)

  convertButton.enabled = !newText.isEmpty
  return true

enter image description here

Alternatively, if you are sure that the user won't press the button when text field is the first responder, you can do the above check in textFieldDidEndEditing(textField:) as well:

func textFieldDidEndEditing(textField: UITextField) {
  convertButton.enabled = textField.text?.isEmpty ?? false

You can play around the test project I created.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download