I have one textfield, & use shouldChangeCharactersInRange
method to get value.
Here is my Code:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSLog(@"Pressing : %@\n", string);
NSMutableString *text = [NSMutableString stringWithString:textField.text];
NSLog(@"length: %lu", (unsigned long)range.length);
NSLog(@"location: %lu\n", (unsigned long)range.location);
NSLog(@"before text: %@", textField.text);
[text replaceCharactersInRange:range withString:string];
NSLog(@"After replacement , Text: %@\n\n", text);
// My work..
return YES;
}
I first add character 'T' to textfield, it works fine ..
2016-03-02 10:06:23.162 MyTextFieldApp[12006:4323645] Pressing : T
2016-03-02 10:06:23.163 MyTextFieldApp[12006:4323645] length: 0
2016-03-02 10:06:23.163 MyTextFieldApp[12006:4323645] location: 0
2016-03-02 10:06:23.163 MyTextFieldApp[12006:4323645] before text:
2016-03-02 10:06:23.163 MyTextFieldApp[12006:4323645] After replacement , Text: T
Then, I backspace it to remove character, that also works fine..
2016-03-02 10:06:30.979 MyTextFieldApp[12006:4323645] Pressing :
2016-03-02 10:06:30.980 MyTextFieldApp[12006:4323645] length: 1
2016-03-02 10:06:30.980 MyTextFieldApp[12006:4323645] location: 0
2016-03-02 10:06:30.980 MyTextFieldApp[12006:4323645] before text: T
2016-03-02 10:06:30.981 MyTextFieldApp[12006:4323645] After replacement , Text:
But, when I am going to add new character then, it crash on replaceString..
Note: This time, Range Gives length 0 & location 1, while first time also when i am adding T to empty textfield, it gives length 0 as well as location 0.
2016-03-02 10:07:02.158 MyTextFieldApp[12006:4323645] Pressing : T
2016-03-02 10:07:02.158 MyTextFieldApp[12006:4323645] length: 0
2016-03-02 10:07:02.159 MyTextFieldApp[12006:4323645] location: 1
2016-03-02 10:07:02.159 MyTextFieldApp[12006:4323645] before text:
2016-03-02 10:07:02.159 MyTextFieldApp[12006:4323645] *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString replaceCharactersInRange:withString:]: Range or index out of bounds'
I can't detect where is the problem?