我有一个UITextField
的实例。我有键盘类型作为数字键盘,因此用户只能输入十进制值。但是我可以输入值 2.4.5.5 。请告诉我如何限制用户只能输入值2.4
答案 0 :(得分:3)
试试这个:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if ([textField.text containsString:@"."] && [string containsString:@"."]) {
return NO;
} else {
return YES;
}
}
答案 1 :(得分:0)
我创建了示例项目,我尝试了。我得到了确切的解决方案。请在下面查看我的答案。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSCharacterSet *charSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
if ([string rangeOfCharacterFromSet:charSet].location != NSNotFound)
return NO;
else {
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
NSArray *arrSep = [newString componentsSeparatedByString:@"."];
if([arrSep count] > 2)
return NO;
else {
if([arrSep count] == 1) {
if([[arrSep objectAtIndex:0] length] > 9)
return NO;
else
return YES;
}
if([arrSep count] == 2) {
if([[arrSep objectAtIndex:0] length] > 9)
return NO;
else if([[arrSep objectAtIndex:1] length] > 2) //Set after dot(.) how many digits you want.I set after dot I want 2 digits.If it goes more than 2 return NO
return NO;
else {
if([[arrSep objectAtIndex:0] length] >= 10) //Again I set the condition here.
return NO;
else
return YES;
}
}
return YES;
}
}
return YES;
}
输出
首先,我根据条件输入带有点的9位数字。
然后我输入你的输入2.4。如果我试图给另一个点它不允许2.4。之后。
答案 2 :(得分:0)
使用它(它对我有用):
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];
NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:string];
BOOL isNumbersOnly = ([numbersOnly isSupersetOfSet:characterSetFromTextField]);
if (!isNumbersOnly) {
return NO;
}
if ([string rangeOfString:@"."].location !=NSNotFound && [textField.text rangeOfString:string].location !=NSNotFound) {
return NO;
}
return YES;
}