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];
}
Read more »Labels: NSScanner, Numeric, UITextField, UITextFieldDelegate
