Reputation: 11
I want the textfield to allow the user to paste only numbers from the alphanumeric text and the same should be displayed.I have already dealt with the keypad part.I have tried the delegate method but it restricts the text altogether ,if it contains any alphabet ,which is not my requirement. I have gone through the discussions but couldn't find what i was looking for.Suggestions please!!
Upvotes: 1
Views: 259
Reputation: 2803
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:characterSet] componentsJoinedByString:@""];
textField.text = filtered;
return NO;
}
Upvotes: 0
Reputation: 5334
Try this
Make a macro
#define ACCEPTABLE_CHARECTERS @"0123456789."
And use it
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField==textFieldAmount)
{
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ACCEPTABLE_CHARECTERS] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
return YES;
}
Upvotes: 1
Reputation: 3928
Check Your textfield containing only numbers or not by using below code :
BOOL valid;
NSCharacterSet *alphaNums = [NSCharacterSet decimalDigitCharacterSet];
NSCharacterSet *inStringSet = [NSCharacterSet characterSetWithCharactersInString:myInputField.text];
valid = [yourTextFieldText isSupersetOfSet:inStringSet];
if (!valid)
{
// Not numeric
}
else
{
//valid number
}
Upvotes: 0