syedfa
syedfa

Reputation: 2819

Trying to delete a character within a string in a UITextField using backspace

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?

Upvotes: 0

Views: 1490

Answers (1)

Automate This
Automate This

Reputation: 31394

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;
}

Upvotes: 1

Related Questions