iPhone, iPod touch, iPad tutorials, examples and sample code. Come and get it!

Tuesday, August 3, 2010

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.

- (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;
NSInteger holder;
and change line 13 from
return [scan scanDouble: &holder] && [scan isAtEnd];
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: , , ,


Post a Comment

Subscribe to Post Comments [Atom]

<< Home

« Older Entries  
Newer Entries »