为UITextField创建通用的下一个按钮

时间:2013-12-24 18:28:47

标签: ios objective-c for-loop tags uitextfield

我正在尝试创建一个与textField标签一起使用的下一个按钮。 我在void类型方法中有这个:

for (UITextField *textField in self.view.subviews)
{
    if ([textField isKindOfClass:[UITextField class]])
    {
        if([textField isFirstResponder])
        {
            int i = _textFieldTag;  //starts as 0

            [[textField viewWithTag:i] resignFirstResponder];
            NSString *a = [(UITextField *)[textField viewWithTag:i] text];
            NSLog(@"TEXT 01 - %@", a);

            i = i + 1;
            NSLog(@"TAG 02 - %i", i);

            [[textField viewWithTag:i] becomeFirstResponder];
            NSString *b = [(UITextField *)[textField viewWithTag:i] text];
            NSLog(@"TEXT 02 - %@", b);
        }
    }
}

问题在于即使i递增1,NSString *b也会返回nil并且不会使textField像我期望的那样成为下一个响应者。

他们在那里,标签存在,但某种程度上不接受i的新值。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

尝试替换以下所有来电:

[textField viewWithTag:i]

为:

[self.view viewWithTag:i]

您应该查看viewWithTag的视图而不是UITextField。

答案 1 :(得分:0)

您的逻辑不正确,正如@Greg所说,您需要使用[self.view viewWithTag:i]来获取正确的视图。另外,为self.view提供一个与任何文本字段标记不同的标记(因为self.view的默认标记为0,所以出现错误)。我想你希望你的逻辑看起来像这样:

-(IBAction)nextField:(id)sender {
    int i;
    for (UITextField *textField in self.view.subviews) {
        if ([textField isKindOfClass:[UITextField class]] && [textField isFirstResponder]) {
            [textField resignFirstResponder];
            NSString *a = textField.text;
            NSLog(@"TEXT 01 - %@", a);
            //i = textField.tag + 1; // use this line if you don't want to go back to the first text field
            i = (textField.tag == 4)? 0 : textField.tag + 1; //use this line if you want to cycle back to the first text field when you are on the last one. Replace the 4 with whatever is your highest tag. This also assumes that the tag of the first text field is 0.  
        }
    }

    NSLog(@"TAG 02 - %i", i);
    [[self.view viewWithTag:i] becomeFirstResponder];
    NSString *b = [(UITextField *)[self.view viewWithTag:i] text];
    NSLog(@"TEXT 02 - %@", b);
}