2

Hello
I know ipad keyboard doesn't like iphone can set "UIKeyboardTypeNumberPad"!!
But if I wanna it only can type and show number 0 to 9 on textfield.
How to compare what user key in on textfield are numbers or not ??

Thank in advance.

Mini

miniHsieh
  • 187
  • 3
  • 9
  • Answered a [similar question here](http://stackoverflow.com/a/12944946/868193). – Beltalowda May 28 '13 at 20:47
  • 1
    Possible duplicate of [Allow only Numbers for UITextField input](https://stackoverflow.com/questions/12944789/allow-only-numbers-for-uitextfield-input) – Beltalowda Jan 29 '19 at 18:55

4 Answers4

9

instead of comparing a figure after it is displayed, do it in the shouldChangeCharactersInRange

be sure to declare the delegate UITextFieldDelegate, and something i always forget, make sure the delegate of the textField itself is pointing at the class that has the code in it.

//---------------------------------------------------------------------------
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string length] == 0 && range.length > 0)
    {
        textField.text = [textField.text stringByReplacingCharactersInRange:range withString:string];
        return NO;
    }

    NSCharacterSet *nonNumberSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
    if ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0)return YES;

    return NO;
}
hokkuk
  • 675
  • 5
  • 21
3

Take a look at this thread. It solved my similar problem.

Community
  • 1
  • 1
Vin
  • 10,257
  • 10
  • 59
  • 70
1

How about How to dismiss keyboard for UITextView with return key??

The idea is you check every time the user hits a key, and if it is a number let it through. Otherwise ignore it.

Make your Controller supports the UITextViewDelegate protocol and implement the textView:shouldChangeTextInRange:replacementText: method.

Community
  • 1
  • 1
Tom
  • 6,567
  • 7
  • 44
  • 72
0
(BOOL) textField: (UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString: (NSString *)string {

    NSNumberFormatter * nf = [[NSNumberFormatter alloc] init];
    [nf setNumberStyle:NSNumberFormatterNoStyle];

    NSString * newString = [NSString stringWithFormat:@"%@%@",textField.text,string];
    NSNumber * number = [nf numberFromString:newString];

    if (number) {
         return YES;

    } else
        return NO;
}
Blazej SLEBODA
  • 6,503
  • 3
  • 35
  • 69