Reputation: 12509
I have a UITextField
where the user should type a float number. I want to check that such number has a certain format I receive, for instance "dddd.dd", where "d" is a digit. The format could change at any moment, since I receive it as input as well, so for example I may want to check at another moment that "," character is used for decimals, to say another example.
Taking into account that the text
you read from the UITextField
is of String
type (optional), what should be the best way to accomplish this?
NumberFormatter
?Upvotes: 0
Views: 391
Reputation: 5967
Try this
in viewDidLoad
or assign delegate to the textfield to self
-(void)viewDidLoad{
self.txtFieldName.delegate = self;
}
Now implement this delegate method -
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(textField == self.txtFieldName)
{
NSCharacterSet *invalidCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"01234567989."] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:invalidCharSet] componentsJoinedByString:@""];
return [string isEqualToString:filtered];
}
else
return YES;
}
This will enable yout textfield to only take numbers from 0-9 and .(decimal).
Upvotes: 1