NSTextField in NSTableCellView - edit end on loss of focus

I have a view with a view based NSTableView (which itself has a cell view with one textbox) and some buttons and textboxes outside of the tableview. One of the buttons adds an object to the data source for the table view, and after inserting a row into the table view, immediately makes it editable.

If the user enters text and hits the return key, I get the - (BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor

fine delegate method and I can run validation and store the value. But the delegate is not called if the user selects any of the other buttons or text boxes outside the table.

What's the best way to detect this loss of focus on a textarea inside an NSTableCellView so I can run some of my confirmation code on the tableview record?

+3


source to share


1 answer


If you understood correctly that you want the notification to control:textShouldEndEditing:

be triggered in the following situation:

  • You are adding a new object to the array controller.
  • The row in the table representing the object is automatically selected.
  • You programmatically select a text box on the appropriate line for editing.
  • The user immediately (i.e. without making any changes to the textbox) focuses on the control elsewhere in the UI


One approach I've used in the past to get this working is to make minor programmatic changes to the textbox-associated field editor just before the textbox becomes editable to the user. The snippet below 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 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)
    }
}

      

+2


source







All Articles