0

我想验证我的 UITextfield 的字符数是否小于 2,并且只应输入数字...... 看到这个

4

5 回答 5

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));
    }
于 2013-06-07T10:02:07.410 回答
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;
    }
}
于 2013-09-25T15:14:56.377 回答
0

在 iOS 中处理此问题的标准方法是将 a 附加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;
}
于 2013-06-07T09:58:44.483 回答
0

试试这样

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if([textField.text length]<2)
        return YES;
    else
        return NO;
}

并将NSNumberkeyboard类型分配给文本字段。

于 2013-06-07T10:02:23.130 回答
0

NSCharaterSet用所有字母声明 a 并检查字段文本是否不包含任何字母的另一种方法:

NSCharacterSet *alphabet = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyz"]
if ([[self.label.text lowercaseString] rangeOfCharacterFromSet:alphabet].location != NSNotFound) 
{
     NSLog(@"Found letters!");
}
于 2013-06-07T10:03:04.820 回答