2015-10-26 29 views
0

我试图以编程方式获取这应该是正在编辑的单元中的一个column.identifier开始检测NSTableColumn选定单元格。我试图通过注册我NSViewController为NSControlTextDidBeginEditingNotification得到,当我得到通知我通过鼠标位置追踪数据:NSTableView的在电池版

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更新正确,我可以去我的模型对象和检测更改在willSet或didSet属性,但我需要检测何时更改是由用户制作,这就是为什么我需要在NSTableView发生变化之前检测到变化。

回答

1

这个问题是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 
}