我试图以编程方式获取正在编辑的单元格的column.identifier。我试图通过为NSControlTextDidBeginEditingNotification注册我的NSViewController来获取通知,并在收到通知时按鼠标位置跟踪数据:

var selectedRow = -1
var selectedColumn: NSTableColumn?

func editingStarted(notification: NSNotification) {
    selectedRow = participantTable.rowAtPoint(participantTable.convertPoint(NSEvent.mouseLocation(), fromView: nil))

    let columnIndex = participantTable.columnAtPoint(participantTable.convertPoint(NSEvent.mouseLocation(), fromView: nil))
   selectedColumn = participantTable.tableColumns[columnIndex]

}


我的问题是鼠标位置给了我错误的数据,是否有一种方法可以基于表的位置来获取鼠标位置,还是有更好的方法来获取此信息?

PS。我的NSViewController是NSTableViewDelegate和NSTableViewDataSource,我的NSTableView是基于视图的,并连接到正确更新的ArrayController,我可以转到我的Model对象,并检测willSet或didSet属性中的更改,但是我需要检测何时进行更改由用户,这就是为什么我需要在NSTableView上检测到更改之前的原因。

最佳答案

这个问题已有1年历史,但今天我有同样的问题并解决。人们在这里为我提供了很多帮助,因此如果有人发现了这个话题,我将做出自己的贡献。
这是解决方案:

1 /将NSTextFieldDelegate添加到您的ViewController中:

class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource, NSTextFieldDelegate {


2 /当用户要编辑单元格时,他必须首先选择该行。因此,我们将使用此委托函数检测到该错误:

    func tableViewSelectionDidChange(_ notification: Notification) {
        let selectedRow = self.tableView.selectedRow

        // If the user selected a row. (When no row is selected, the index is -1)
        if (selectedRow > -1) {
        let myCell = self.tableView.view(atColumn: self.tableView.column(withIdentifier: "myColumnIdentifier"), row: selectedRow, makeIfNecessary: true) as! NSTableCellView

        // Get the textField to detect and add it the delegate
        let textField = myCell.textField
        textField?.delegate = self
    }
}


3 /当用户编辑单元格时,我们可以使用3种不同的功能来获取事件(和数据)。选择您需要的:

override func controlTextDidBeginEditing(_ obj: Notification) {
    // Get the data when the user begin to write
}

override func controlTextDidEndEditing(_ obj: Notification) {
    // Get the data when the user stopped to write
}

override func controlTextDidChange(_ obj: Notification) {
    // Get the data every time the user writes a character
}

10-08 03:18