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
Put shouldChangeCharactersIn function outside of viewDidLoad, and check in it if character are > 2:
Your
shouldChangeCharactersIn
method is inside ofviewDidLoad
. This means it doesn’t actually implement the delegate method that you want to implement. You should move it outside, at the same level asviewDidLoad
.Also, because of how
shouldChangeCharactersIn
works, the text field’stext
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.