Question

I need to delete a character from an NSString when an NSRange is specified. I have a text field and I enter some text with number formatting and I get the value as $1,234,567.00.

Now i place my cursor after digit 5 and want to delete the number 5. In the Text delegate method shouldChangeCharactersInRange I get the range as (7,1) when I press backspace. I tried the following

modifiedFieldText = [modifiedFieldText stringByReplacingCharactersInRange:NSMakeRange(range.location - 1, range.length) withString:string];

But I am not able to delete the correct character. Any suggestion on this would be of great help. Please correct me where I went wrong.

Was it helpful?

Solution

I suspect that you must have some line of code that is modifying modifiedFieldText before you get to this line. You should make sure that the range is applied to the original textField contents, achieved by making the stringByReplacingCharactersInRange use the textfield directly, such as:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *modifiedFieldText = [textField.text stringByReplacingCharactersInRange:range withString:string];

    // now do whatever else you want
}

With that code, if the text field contained $1,234,567.00 and the user deleted the 5, the range would be {7, 1}, and the resulting modifiedFieldText would be $1,234,67.00, which you can presumably proceed and reformat to adjust the punctuation as you see fit.

If you are still having troubles, update your question with a more complete rendition of your shouldChangeCharactersInRange.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top