swiftxcodeuitextfielddelegate

How to enable addButton when corresponding textField has 3+ characters typed in?


I have a textField and a submit button. The submit button is disabled by default and should only be enabled if textField has 3+ characters typed into it.

My code:

class AddNameVC: UITableViewController, UITextFieldDelegate {
    
    @IBOutlet weak var addNameTF: UITextField!
    @IBOutlet weak var addButton: UIButton!
    @IBAction func addButton(_ sender: Any) {
        performSegue(withIdentifier: "unwindToAllNames", sender: self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addNameTF.delegate = self
        addButton.isEnabled = false
        
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            addButton.isEnabled = addNameTF.text!.count > 2
            return true
        }
    }
}

After typing 3+ characters into the textField, button remains disabled. In fact, it never turns enabled no matter how many characters I type in.

What am I doing wrong?


Solution

  • Your shouldChangeCharactersIn method is inside of viewDidLoad. This means it doesn't actually implement the delegate method that you want to implement. You should move it outside, at the same level as viewDidLoad.

    Also, because of how shouldChangeCharactersIn works, the text field's text has not been updated with the new text when it is called. You should instead compute the new text and use that to determine whether to enable the button.

    override func viewDidLoad() {
        // ...
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        addButton.isEnabled = newText.count > 2
        return true
    }