Textfield Delegate Shouldchangecharactersinrange

TextField delegate shouldChangeCharactersInRange

That method is asking you if it should take the replacementString and add it onto textField.text. It is called immediately after you press a key on the keyboard and before letter appears on screen.

To see what the new string will be, you'd need to to something like this.

let newText = textField.text.stringByReplacingCharactersInRange(range, withString: string)
print(newText)

Textfield shouldchangecharactersinrange swift

You could use a target on your textField with the control event EditingChanged instead of the delegate method.

Swift >= 1.0

myTextField.addTarget(self, action: "didChangeText:", forControlEvents: .EditingChanged)

Swift 3.0 (String literal selectors are deprecated, use #selector)

myTextField.addTarget(self, action: #selector(didChangeText(_:)), for: .editingChanged)

Then use the targeted method to run your checks.

func didChangeText(textField:UITextField) {
if textField.text == "apple" {
checkImageView1.hidden = false
} else {
checkImageView1.hidden = true
}
}

TextField delegate method shouldChangeCharactersInRange not called for chinese text

I had this issue in my App too. May be it's bug of iOS, i don't know.

I used this solution:

1) I made "Editing Changed" IBOutlet from my UITextField to class file.

Sample Image

2) I described all logic in this - (IBAction)textFieldDidChanged:(id)sender method.

3) In your case, it's would be:

if (_textField.text.length > 6) {
_btnNext.enabled = NO;
} else {
_btnNext.enabled = YES;
}

UITextField shouldChangeCharactersInRange fires twice?

Setting breakpoints in that delegate method can sometimes cause the method to be fired twice. Try removing any breakpoints that are hit here or in your API method and test again.


This can be replicated easily. Create a new project, add a UITextField outlet and set the delegate to your controller. Implement textField:shouldChangeCharactersInRange: in your controller and set a breakpoint on an NSLog statement or something, and return YES. Sometimes, after telling the debugger to continue, a second keystroke will be generated and will hit your delegate method again.

How shouldChangeCharactersInRange works in Swift?

Swift 4, Swift 5

This method doesn't use NSString

// MARK: - UITextFieldDelegate

extension MyViewController: UITextFieldDelegate {
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
if let text = textField.text,
let textRange = Range(range, in: text) {
let updatedText = text.replacingCharacters(in: textRange,
with: string)
myvalidator(text: updatedText)
}
return true
}
}

Note. Be careful when you use a secured text field.



Related Topics



Leave a reply



Submit