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);
}
- (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);
}
}
- (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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With