UITextField: Only allow numeric entry using NSScanner
Have a UITextField and want to prevent the user from entering anything but numbers (and decimal point)? This quick function utilizing the UITextFieldDelegate will do the trick.
If you want an integer instead of a double, change line 10 from
Remember, in order for this method to be called, you have to reference the delegate class in your header file and set the delegate property of the UITextField to self.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string]; // This allows backspace if ([resultingString length] == 0) { return true; } double holder; NSScanner *scan = [NSScanner scannerWithString: resultingString]; return [scan scanDouble: &holder] && [scan isAtEnd]; }
If you want an integer instead of a double, change line 10 from
double holder;to
NSInteger holder;and change line 13 from
return [scan scanDouble: &holder] && [scan isAtEnd];to
return [scan scanInteger: &holder] && [scan isAtEnd];
Remember, in order for this method to be called, you have to reference the delegate class in your header file and set the delegate property of the UITextField to self.
@interface MyViewController : UIViewController<UITextFieldDelegate> { }
self.myTextField.delegate = self;
Labels: NSScanner, Numeric, UITextField, UITextFieldDelegate
3 Comments:
Exactly what I was looking for!
Where do you write the self.myTextField.delegate = self; ?
By Seb, At February 1, 2011 at 7:11 AM
Seb,
You can set the delegate in a number of places. I usually do it (void)viewDidLoad{}. Hope that helps!
tk
By tk, At February 17, 2011 at 1:59 PM
thnx a lot work superbly
By Unknown, At January 27, 2014 at 9:32 AM
Post a Comment
Subscribe to Post Comments [Atom]
<< Home