Reputation: 115
I am making an app i want that when user inputs any data then whatever user enter like if he enters a so it does not take this input and show nothing in textfield and if it enter any number then it should accept.
Upvotes: 1
Views: 308
Reputation: 350
NSUInteger lengthOfString = string.length;
for (NSInteger loopIndex = 0; loopIndex < lengthOfString; loopIndex++) {
unichar character = [string characterAtIndex:loopIndex];
if (character < 48) return NO; // 48 unichar for 0
if (character > 57) return NO; // 57 unichar for 9
}
this is the code should be written in textfield should change characters inrange
Upvotes: 0
Reputation: 1517
Following code should help you, this will not allow any other text to be entered in your text field other than numbers.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
static NSCharacterSet *charSet = nil;
if(!charSet) {
charSet = [[[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet] retain];
}
NSRange strLocation = [string rangeOfCharacterFromSet:charSet];
return (strLocation.location == NSNotFound);
}
Upvotes: 4
Reputation: 4750
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField.tag==3)
{
NSUInteger lengthOfString = string.length;
for (NSInteger loopIndex = 0; loopIndex < lengthOfString; loopIndex++)
{
unichar character = [string characterAtIndex:loopIndex];
if (character < 46 || character==47)
return NO;
if (character > 57)
return NO;
}
}
Set tag to your textField.
Upvotes: 0
Reputation: 1501
Why do u do this better give a keyboard style
[txtField setKeyboardType:UIKeyboardTypeNumberPad]
or u can do it programatically :
NSString *nameRegex = @"[0-9]*";
NSPredicate *nameTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", nameRegex];
BOOL value = [nameTest evaluateWithObject:string];
if(value == YES)
{
// Do Somethings
}
else
{
// Do something
}
Upvotes: 2
Reputation: 2312
you need to set keyboard type of Textfield as Numberpad.
Try this using code : (also u can set with Inter face builder on XIB property)
[txtFieldObj setKeyboardType:UIKeyboardTypeNumberPad];
Upvotes: 0