【问题标题】:Why is UITextField's window nil?为什么 UITextField 的窗口为零?
【发布时间】:2012-06-06 23:38:22
【问题描述】:

我正在尝试为一系列UITextFields 实现“上一个”、“下一个”和“完成”按钮,每个按钮都包含在一个分组UITableView 中的UITableViewCell 中。我在NSMutableArray 中保留UITextFields,并保留一个指向当前活动的UITextField 的整数。这是分别在点击上一个和下一个按钮时触发的两个选择器。

-(IBAction)didSelectPreviousButton:(id)sender
{    
    if ((textFieldIndex - 1) >= 0) {
        UITextField *currentField = [self.testTextFields objectAtIndex:(textFieldIndex)];
        UITextField *nextTextField = [self.testTextFields objectAtIndex:(--textFieldIndex)];
        BOOL result = [nextTextField becomeFirstResponder];
        NSLog([NSString stringWithFormat:@"currentField's window: %@", currentField.window]);
        NSLog([NSString stringWithFormat:@"nextTextField's window: %@", nextTextField.window]);
    } else {
        [self dismissKeyboard:sender];
    }
}

-(IBAction)didSelectNextButton:(id)sender
{
    if ((textFieldIndex + 1) < [self.inspectionItemSpec.numberOfTests intValue]) {
        UITextField *currentField = [self.testTextFields objectAtIndex:(textFieldIndex)];
        UITextField *nextTextField = [self.testTextFields objectAtIndex:(++textFieldIndex)];
        BOOL result = [nextTextField becomeFirstResponder];
        NSLog([NSString stringWithFormat:@"currentField's window: %@", currentField.window]);
        NSLog([NSString stringWithFormat:@"nextTextField's window: %@", nextTextField.window]);
    } else {
        [self dismissKeyboard:sender];
    }
}

如您所见,我正在记录当前和下一个文本字段的窗口属性,并且在didSelectNextButton 中,一切都是正确的。但是,在didSelectPreviousButton 中,nextTextField.window 始终是nil。为什么会发生这种情况?

(请注意,只有在用户点击下一个按钮一次后,才会启用上一个按钮。)

【问题讨论】:

    标签: iphone ios cocoa-touch uikit uitextfield


    【解决方案1】:

    这可能是因为每个UITextField 都在UITableViewCell 中,同时也在self.testTextFields 中被引用。由于 iOS 中的表格重复使用单元格的方式,您可能(并且可能会)最终遇到数组中的下一个文本字段不是表格中下一个可见行中的文本字段的情况。

    如果您发布您的tableView:cellForRowAtIndexPath: 代码,这可能会使问题变得明显。

    【讨论】:

    • 这让我走上了正轨。我向becomeFirstResponder 请求的textField 已经滚出屏幕,因此它的window 属性返回nil。
    【解决方案2】:

    窗口是视图层次结构的根。如果 window 属性为 nil,则该视图尚未通过类似的方式添加到视图层次结构中

        [someViewInTheViewHierarchy addSubview:yourView].
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-02
      • 2014-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多