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
IPad - how to only type 0~9 on textfield?
提问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 Tom
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.
让你的控制器支持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;
}