skip to Main Content

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?

2

Answers


  1. Put shouldChangeCharactersIn function outside of viewDidLoad, and check in it if character are > 2:

    override func viewDidLoad() {
        super.viewDidLoad()
        
        addNameTF.delegate = self
        addButton.isEnabled = false
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField.text?.count ?? 0 >= 2 {
            print("textfield = 3 charachters")
            addButton.isEnabled = true
        }
        return true
    }
    
    Login or Signup to reply.
  2. 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
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search