How do I detect if a text field has text in it rather than a numerical value?

拟墨画扇 提交于 2019-12-10 12:24:49

问题


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.

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.


回答1:


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:@""];
}  

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

EDITE:

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




回答2:


Simply disallowing entry of non-numeric characters is one way. But what you asked is how do you detect non-numerics...

Use

NSRange range = [myTextField.text rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
if(range.location == NSNotFound) {
    // then it is numeric only
}



回答3:


NSRange    range    =    [myTextField.text    rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];


来源:https://stackoverflow.com/questions/23259569/how-do-i-detect-if-a-text-field-has-text-in-it-rather-than-a-numerical-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!