如何检测文本字段中是否包含文本而不是数值? [英] How do I detect if a text field has text in it rather than a numerical value?

查看:137
本文介绍了如何检测文本字段中是否包含文本而不是数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本字段,用户输入一个数字,并将其转换为整数。

I have a text field which the user enters a number and it gets converted to an integer.

键盘设置为十进制数字。

The keyboard set is to decimal numerical one. Except the paste function is still enabled so the user can paste text into it.

我想将其设置为将标签更改为@错误,如果用户输入了非数值。

I want to set it to change a label to @"error" if the user enters a non numerical value into it.

我不想禁用粘贴功能,因为我仍然希望用户能够复制和粘贴自己的数值到我的app。

I do not want to disable the paste function as I still want the user to have the ability to copy and paste their own numerical values into my app.

推荐答案

如果您希望应用限制,只能使用输入数值,请使用 UITextField

If you want apply restriction that use have to only enter numeric value then use delegate method of UITextField:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
   NSCharacterSet *nonNumberSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
   return ([string stringByTrimmingCharactersInSet:nonNumberSet].length > 0) || [string isEqualToString:@""];
}  

这将返回 YES ,否则返回 NO

This will returns YES if the string is numeric, otherwise return NO.

EDITE

@ Adam's 的答案是最好的检查文本只是数字或不是。

@Adam's answer is the best for check text is only numeric or not.

这篇关于如何检测文本字段中是否包含文本而不是数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆