如何在文本字段中添加最小文本

时间:2014-04-16 11:43:49

标签: objective-c ios5

我有三种类型的文本字段。因为我只需要最少的数字。下面的代码我写入但它不起作用。帮助我

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ 
    if (country.text.length <= 4) {
        return YES;
    }

    if(code.text.length<=4 ) {
        return YES;
    }

    if(textPhone.text.length<=10) {
        return YES;
    }

    return YES;
}

2 个答案:

答案 0 :(得分:3)

你的逻辑存在缺陷。您甚至不会根据编辑哪个字段来确定支票。

试试这个:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ 

    // Allow backspace anyway
    if (range.length == 0)
        return YES;

    if (textField == country)
        return (country.text.length <= 4);

    else if (textField == code)
        return (code.text.length <= 4);

    else if (textField == textPhone)
        return (textPhone.text.length <= 10);

    // Default for all other fields
    return YES;
}

答案 1 :(得分:0)

首先,这似乎绝对毫无意义,因为你在每种情况下都会返回YES,所以为什么要费心去追查if statement,但如果你坚持这样做,请尝试下面的任何一个。

初始化UITextFields后,请设置以下内容

... Initilization code for country, textPhone and code.
[country setTag:1001];
[code setTag:1002];
[textPhone setTag:1003];

并在shouldChangeCharactersInRange:方法中

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ 
    switch([textField tag]) {
        case 1001:
                  // Do whatever 
                  return (textField.text.length <= 4);
        case 1002:
                  // Do whatever
                  return (textField.text.length <= 4);
        case 1003:
                  // Do whatever
                  return (textField.text.length <= 10);
        default:
                return YES;
    }
}

如果您想使用if语句继续尝试

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ 
    if((([textField tag] == 1001 || [textField tag] == 1002) && [textField text].length <= 4) || ([textField tag] == 1003 && [textField text].length <= 10)) {
        return ((([textField tag] == 1001 || [textField tag] == 1002) && [textField text].length <= 4) || ([textField tag] == 1003 && [textField text].length <= 10));
    }
    return YES;
}