TextField:shouldChangeCharactersInRange:replacementString:return trap!

时间:2011-05-11 04:01:18

标签: iphone uitableview uitextfield

我调用UITableViewCell委托方法TextField:shouldChangeCharactersInRange:replacementString:在一个包含四个UITextFields的自定义单元格上,一旦在其中一个字段上达到maxlength就会发生什么,它不允许您在其他字段中输入任何文本,因为它总是对于满足的初始if语句,返回“no”。关于如何解决这个问题的任何想法?

我目前只在两个领域进行测试。感谢您提前提供任何帮助。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    int regFieldOnelength = [regFieldOne.text length] ;
    int regFieldTwolength = [regFieldTwo.text length] ;


    if ((regFieldOnelength >= MAXLENGTH && ![string isEqualToString:@""]) || (regFieldTwolength >= MAXLENGTH && ![string isEqualToString:@""])) {
        if(regFieldOne.text = [regFieldOne.text substringToIndex:MAXLENGTH]){
            return NO;
        }
        if(regFieldTwo.text = [regFieldTwo.text substringToIndex:MAXLENGTH]){
            return NO;
        }
    }


    return YES;
}

2 个答案:

答案 0 :(得分:4)

为什么使用booth文本字段,而是使用正在编辑的当前文本字段

    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
        int currentTxtLen = [textField.text length] ;
        if (currentTxtLen >= MAXLENGTH && ![string isEqualToString:@""]) {
            return NO;
        }
        return YES;
}

答案 1 :(得分:0)

你能试试吗

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    int regFieldOnelength = [regFieldOne.text length] ;
    int regFieldTwolength = [regFieldTwo.text length] ;

if((textField == regFieldOne) ||(textField == regFieldTwo)) {

    if ((regFieldOnelength >= MAXLENGTH && ![string isEqualToString:@""]) || (regFieldTwolength >= MAXLENGTH && ![string isEqualToString:@""])) {
        if(regFieldOne.text = [regFieldOne.text substringToIndex:MAXLENGTH]){
            return NO;
        }
        if(regFieldTwo.text = [regFieldTwo.text substringToIndex:MAXLENGTH]){
            return NO;
        }
    }


    return YES;
}
    else {
      return YES;
    }
}