问题
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