我想验证我的UITextfield小于2的字符数,只输入数字... seen this
答案 0 :(得分:6)
试试这个...
#define NUMBERS_ONLY @"1234567890"
#define CHARACTER_LIMIT 2
并以此方法----
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSUInteger newLength = [textField.text length] + [string length] - range.length;
NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];
NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
return (([string isEqualToString:filtered])&&(newLength <= CHARACTER_LIMIT));
}
答案 1 :(得分:1)
这有效!!
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([string isEqualToString:@""]) return YES;
unichar c = [string characterAtIndex:0];
if ([[NSCharacterSet decimalDigitCharacterSet] characterIsMember:c])
{
int maxVal = 2;
if (textField.text.length >= maxVal)
return NO;
else
return YES;
} else {
return NO;
}
}
答案 2 :(得分:0)
在iOS中处理此问题的标准方法是将UITextFieldDelegate
附加到UITextField
,并实施textField:shouldChangeCharactersInRange:replacementString:
方法。在此方法中,您可以验证字符串
使用属性length
来实现此目的
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if([textField.text length]<2)
return YES;
else
return NO;
}
答案 3 :(得分:0)
尝试这样,
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if([textField.text length]<2)
return YES;
else
return NO;
}
并将NSNumberkeyboard
类型指定给文本字段。
答案 4 :(得分:0)
使用所有字母声明NSCharaterSet
的另一种方法,并检查字段的文本是否包含任何字母:
NSCharacterSet *alphabet = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyz"]
if ([[self.label.text lowercaseString] rangeOfCharacterFromSet:alphabet].location != NSNotFound)
{
NSLog(@"Found letters!");
}