0

textField我正在通过有两个对象创建一个具有邮政编码字段的应用程序。像这样,

在此处输入图像描述

现在我希望我的第一个textField允许我在该控件进入第二个之后输入 5 个字符textField。在第二个文本字段中,我只能输入 4 个字符,之后它将不接受任何字符。

我试过这段代码

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
if (textField == zipCode1TV) {
        txtFieldSelected = @"zipCode1TV";
    } else if(textField == zipCode2TV){
        txtFieldSelected = @"zipCode2TV";
    }
    return YES;
}

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

    if ([txtFieldSelected isEqual: @"zipCode1TV"]) {
        if (zipCode1TV.text.length>4) {
            [zipCode2TV becomeFirstResponder];
        }
    }
    if ([txtFieldSelected isEqual: @"zipCode2TV"]) {
        int maxChar = 4;
        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        return (newLength <= maxChar);
    }
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{

    if ([txtFieldSelected isEqual: @"zipCode2TV"] ||[txtFieldSelected isEqual: @"zipCode2TV"]) {
        zipCode =[NSString stringWithFormat:@"%@%@",zipCode1TV.text,zipCode2TV.text];
        NSLog(@"%@",zipCode);
    }
} 

使用这段代码我解决了一些问题,但我无法重新输入第一个textField,我的字符串zipCode没有返回实际值;当控件从第一个textField变为第二个时,它会跳过一个值textField

4

1 回答 1

1

答案在您的问题中,使用您的代码,但我已对其进行了修改,

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
if (textField == zipCode1TV) {
        txtFieldSelected = @"zipCode1TV";
    } else if(textField == zipCode2TV){
        txtFieldSelected = @"zipCode2TV";
    }
    return YES;
}

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

    if ([txtFieldSelected isEqual: @"zipCode1TV"]) {
        //here set the maximum character length and transfer control when newLength exceed maxChar
         int maxChar = 5;
        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        if (newLength >5) {
            zipCode2TV.text = string;
            [zipCode2TV becomeFirstResponder];
        }
        return (newLength <= maxChar);
    }
    if ([txtFieldSelected isEqual: @"zipCode2TV"]) {
        int maxChar = 4;
        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        return (newLength <= maxChar);
    }
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{

    if ([txtFieldSelected isEqual: @"zipCode2TV"] ||[txtFieldSelected isEqual: @"zipCode2TV"]) {
        zipCode =[NSString stringWithFormat:@"%@%@",zipCode1TV.text,zipCode2TV.text];
        NSLog(@"%@",zipCode);
    }
} 
于 2013-06-10T05:56:35.287 回答