Reputation: 83
I'm building a simple Welcome page that has a Name & Age text input field. I was able to successfully limit the character input count on the name field, but using the same logic on the age field has not worked at all. Thoughts?
class WelcomeViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var ageTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
nameTextField.delegate = self
ageTextField.delegate = self
}
// Character Count Code UITextField
func textField(_ nameTextField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// get the current text, or use an empty string if that failed
let currentText = nameTextField.text ?? ""
// attempt to read the range they are trying to change, or exit if we can't
guard let stringRange = Range(range, in: currentText) else { return false }
// add their new text to the existing text
let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
// make sure the result is under # characters
return updatedText.count <= 30
}
func textField2(_ ageTextField: UITextField, shouldChangeCharactersIn range2: NSRange, replacementString string2: String) -> Bool {
// get the current text, or use an empty string if that failed
let currentText2 = ageTextField.text ?? ""
// attempt to read the range they are trying to change, or exit if we can't
guard let stringRange2 = Range(range2, in: currentText2) else { return false }
// add their new text to the existing text
let updatedText2 = currentText2.replacingCharacters(in: stringRange2, with: string2)
// make sure the result is under # characters
return updatedText2.count <= 2
}
Upvotes: 0
Views: 219
Reputation: 52397
The delegate method has a specific signature (textField(_:shouldChangeCharactersIn:replacementString:)
) that is called by the system. Your first function uses that pattern.
Your second one, currently, does not, since you've named it textField2
-- the system has no reason to know to call something starting with that prefix.
Instead, you should probably use a single function and then have it behave differently based on which UITextField
is sent in to the first parameter:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == nameTextField {
//content
}
if textField == ageTextField {
//content
}
}
This could obviously be an else if
, or even just an else
if you stay limited to 2 text fields. Within the if
block, you could either call out to a separate, specialized function, or keep all of your logic within the if
block.
Example with switch
:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
switch textfield {
case nameTextField:
//content
case ageTextField:
//content
default:
return true
}
}
Upvotes: 3