3

我有一个基于视图的 NSTableView 视图(它本身有一个带有单个文本字段的单元格视图)以及表格视图之外的一些按钮和文本字段。其中一个按钮将一个对象添加到 tableview 的数据源中,并且在将行插入 tableview 后,立即使其可编辑。

如果用户输入文本并按下返回键,我会收到- (BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor委托方法,我可以运行验证并保存值。但是,如果用户选择了 tableview 之外的任何其他按钮或文本字段,则不会调用委托。

检测 NSTableCellView 内的文本字段失去焦点的最佳方法是什么,以便我可以在 tableview 条目上运行一些验证代码?

4

1 回答 1

2

If I understand you correctly you want a control:textShouldEndEditing: notification to fire in the following situation:

  1. You add a new object to the array controller.
  2. The row in the table representing the object is automatically selected.
  3. YOU programmatically select the text field in the relevant row for editing.
  4. The user immediately (i.e. without making any edits in the text field) gives focus to a control elsewhere in the UI

One approach I've used in the past to get this working is to make an insignificant programmatic change to the field editor associated with the text field, just before the text field becomes available to the user for editing. The snippet below shows how to do this - this is step 2/step 3 in the above scenario:

func tableViewSelectionDidChange(notification: NSNotification) {
    if justAddedToArrayController == true {
        // This change of selection is occurring because the user has added a new
        // object to the array controller, and it has been automatically selected 
        // in the table view. Now need to give focus to the text field in the 
        // newly selected row...

        // Access the cell
        var cell = tableView.viewAtColumn(0,
            row: arrayController.selectionIndex,
            makeIfNecessary: true) as NSTableCellView

        // Make the text field associated with the cell the first responder (i.e. 
        // give it focus)
        window.makeFirstResponder(cell.textField!)

        // Access, then 'nudge' the field editor - make it think it's already
        // been edited so that it'll fire 'should' messages even if the user 
        // doesn't add anything to the text field
        var fe = tableView.window?.fieldEditor(true, forObject: cell.textField!)
        fe!.insertText(cell.textField!.stringValue)
    }
}
于 2014-12-06T23:25:04.960 回答