Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backspace not working when implementing shouldChangeCharactersInRange method - iPhone Dev

Problem... I have a string of allowable characters "0123456789." How do I also allow the backspace from the keyboard... when I implement the code from below... the backspace key no longer works... How can I fix this?

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

    NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];

    return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);

}
like image 696
Ben Call Avatar asked Apr 29 '10 14:04

Ben Call


3 Answers

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];

    if (range.length == 1){
        return YES;
    }else{
        return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0);
    }


}
like image 160
Ben Call Avatar answered Nov 19 '22 13:11

Ben Call


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string length] == 0) 
        return YES; 

    NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    string = [[string componentsSeparatedByCharactersInSet:nonNumberSet] componentsJoinedByString:@""]; 
    textField.text = [textField.text stringByReplacingCharactersInRange:range withString:string]; 

    return NO; 
}

This should work correctly with deleting/cutting multiple characters at once, as well as pasting. Corrections welcome. The only known problem is that when you edit in the middle of the text field the cursor gets sent to the end (because it returns NO) -- I guess you have to use a UITextView to fix that.

like image 22
jlstrecker Avatar answered Nov 19 '22 11:11

jlstrecker


NSCharacterSet *theNonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];


        if (range.length == 1){
            return YES;
        }else if(textField.text.length < ZipcodeTextLength)
        {
            return ([string stringByTrimmingCharactersInSet:theNonNumberSet].length > 0);
        }
        else
            return NO;

This will allow Numbers and Backspace and also you can limit the text length.

like image 44
Saurav Avatar answered Nov 19 '22 11:11

Saurav