0

I have a UITextField in my application where I allow the user to enter and delete text. I am implementing the UITextFieldDelegate method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{ }

Inside this method, I do a few things (unrelated to this question), and then call another method:

-(NSString*) formatString:(NSString*) stringName stringRange:(NSRange)range deleteLastChar:(BOOL)deleteLastChar {

    ...

    NSString *newString = [stringName mutableCopy];
    if(deleteLastChar) {
        //this line below is only deleting spaces within the text, but not deleting any characters.  I am unable to position the cursor in front of any character within the line itself, but only at the end of the line.  I am only able to delete characters from the end of the end of the line, but not from within the line.
        [newString delecteCharactersInRange:NSMakeRange(range.location, 1)];
    }

    return newString;

}

In this method, I am trying to delete the character the cursor is next to using the backspace key of the keypad (standard functionality). "stringName" in this case is the entire string entered in the textField. Instead, I am always deleting the last character of the entire string. I realize I need to use the NSRange object, but I am not sure how in this case. Any ideas?

halfer
  • 19,824
  • 17
  • 99
  • 186
syedfa
  • 2,801
  • 1
  • 41
  • 74

1 Answers1

1

Here is one way of doing it which is using the UITextField rather than just the string

-(void)RemoveCharacter{
    // Reference UITextField
    UITextField *myField = _inputField;

    UITextRange *myRange = myField.selectedTextRange;
    UITextPosition *myPosition = myRange.start;
    NSInteger idx = [myField offsetFromPosition:myField.beginningOfDocument toPosition:myPosition];

    NSMutableString *newString = [myField.text mutableCopy];

    // Delete character before index location
    [newString deleteCharactersInRange:NSMakeRange(--idx, 1)];

    // Write the string back to the UITextField
    myField.text = newString;
}
Automate This
  • 30,726
  • 11
  • 60
  • 82
  • Thanks so much for your solution. It is almost working, but my only problem is that the cursor is always returning to the end of the line instead of the place where the deleted character was. Any suggestions? – syedfa Aug 07 '14 at 21:35
  • Good question, I think this [post](http://stackoverflow.com/a/11532718/2521004) has what you need. If not, let me know and I'll dig into it further. – Automate This Aug 07 '14 at 21:41
  • I've updated my code above to show you what I have. I am at least able to delete spaces within the line, but not any characters. I'm only able to delete characters from the end of the line. Thanks again for all of your help. – syedfa Aug 08 '14 at 21:12