2014-12-05 61 views
3

我有一个基于视图的NSTableView(其本身具有单个文本字段的单元格视图)以及一些按钮和文本字段以外的视图。其中一个按钮将一个对象添加到tableview的数据源中,并将该行插入到tableview后立即使其可编辑。NSTableCellView中的NSTextField - 在失去焦点时进行编辑

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

什么是最好的方式来检测NSTableCellView内的文本的这种失去焦点,所以我可以运行一些我的验证码在tableview条目?

回答

2

如果我理解正确你想control:textShouldEndEditing:通知解雇在以下情况:

  1. 您添加一个新的对象到阵列控制器。
  2. 表中表示对象的表中的行被自动选中。
  3. 您以编程方式选择相关行中的文本字段进行编辑。
  4. 用户立即(即没有在文本字段进行任何编辑)给出了焦点中我已经在过去使用得到这个工作的UI

一种方法其它地方的控制是为了一个微不足道在文本字段变得可供用户进行编辑之前,对与文本字段相关联的字段编辑器进行编程改变。下面的代码段示出了如何做到这一点 - 这是步骤2/步骤3在上述情形:

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) 
    } 
}