xcode iPad - 如何在文本字段上只输入 0~9?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5931910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 20:59:51  来源:igfitidea点击:

IPad - how to only type 0~9 on textfield?

xcodeipaduitextfield

提问by miniHsieh

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 ??

你好
我知道 ipad 键盘不喜欢 iphone 可以设置“UIKeyboardTypeNumberPad”!!
但是如果我想要它只能在文本字段上输入和显示数字 0 到 9。
如何比较用户在文本字段中输入的内容是数字还是不是数字?

Thank in advance.

预先感谢。

Mini

小型的

回答by hokkuk

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

不要在显示后比较图形,而是在 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.

一定要声明委托 UITextFieldDelegate,还有一些我总是忘记的东西,确保 textField 本身的委托指向包含代码的类。

//---------------------------------------------------------------------------
- (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;
}

回答by Vin

Take a look at thisthread. It solved my similar problem.

看看这个线程。它解决了我的类似问题。

回答by Tom

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

如何使用返回键关闭 UITextView 的键盘??

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 UITextViewDelegateprotocol and implement the textView:shouldChangeTextInRange:replacementText:method.

让你的控制器支持UITextViewDelegate协议并实现textView:shouldChangeTextInRange:replacementText:方法。

回答by Adobels

(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;
}