The following code works but applies to all TextFields. How can I limit it to one specific TextField?
Code:
func textField(_ textField:
Assuming that you have two textFields and your controller is a delegate of both.
@IBOutlet var aMagesticTextField: UITextField!
@IBOutlet var anotherMagesticTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
aMagesticTextField.delegate = self
anotherMagesticTextField.delegate = self
}
In shouldChangeCharactersIn, check the textField parameter against your known text fields.
if textField == aMagesticTextField {
//It's aMagesticTextField
}
else {
//It's anotherMagesticTextField
}
1) Implement the code you referenced in the UITextFieldDelegate implementation for only that one TextField. I strongly prefer this option.
2) Conditionally check for something that uniquely identifies the TextField you are interested in such as its tag property. Only run the character count check for that TextField. Otherwise, default to true.
I never use the tag property for identifying a UI element and don't suggest it. However, I see it used often.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Set textField tag to 9 if you want pass this guard
guard textField.tag == 9 else {
return true
}
let currentCharacterCount = (textField.text?.characters.count) ?? 0
if (range.length + range.location > currentCharacterCount){
return false
}
let newLength = currentCharacterCount + string.characters.count - range.length
return newLength <= 9
}