【问题标题】:Creating a generic next button for UITextField为 UITextField 创建一个通用的下一步按钮
【发布时间】:2013-12-24 18:28:46
【问题描述】:

我正在尝试创建一个与 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 的新值不被接受。

有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

    尝试替换所有来自:

    [textField viewWithTag:i]
    

    到:

    [self.view viewWithTag:i]
    

    您应该向视图询问 viewWithTag 而不是 UITextField。

    【讨论】:

    • 抱歉让应用崩溃了
    • *** 由于未捕获的异常 'NSInvalidArgumentException' 导致应用程序终止,原因:'-[UIView text]: unrecognized selector sent to instance 0x8c15ca0'
    【解决方案2】:

    您的逻辑不正确,正如@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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 2017-07-14
      相关资源
      最近更新 更多