Using `textField:shouldChangeCharactersInRange:`, how do I get the text including the current typed character?
-shouldChangeCharactersInRange
gets called before text field actually changes its text, that's why you're getting old text value. To get the text after update use:
[textField2 setText:[textField1.text stringByReplacingCharactersInRange:range withString:string]];
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSLog(@"%@",searchStr);
return YES;
}
Swift 3
Based on the accepted answer, the following should work in Swift 3:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newString = NSString(string: textField.text!).replacingCharacters(in: range, with: string)
return true
}
Note
Both String
and NSString
have methods called replacingCharacters:inRange:withString
. However, as expected, the former expects an instance of Range
, while the latter expects an instance of NSRange
. The textField
delegate method uses an NSRange
instance, thus the use of NSString
in this case.