打印用户单击的行的NSTableView的行号

时间:2015-03-22 18:32:16

标签: swift macos cocoa nstableview nstableviewcell

我有一列NSTableView。我想打印用户点击的行的行号。我不知道我应该从哪里开始。有没有办法呢?

2 个答案:

答案 0 :(得分:16)

您可以使用NSTableView委托中selectedRowIndexes方法中tableView的tableViewSelectionDidChange属性。

在此示例中,tableView允许多个选择。

Swift 3

func tableViewSelectionDidChange(_ notification: Notification) {
    if let myTable = notification.object as? NSTableView {
        // we create an [Int] array from the index set
        let selected = myTable.selectedRowIndexes.map { Int($0) }
        print(selected)
    }
}

Swift 2

func tableViewSelectionDidChange(notification: NSNotification) {
    var mySelectedRows = [Int]()
    let myTableViewFromNotification = notification.object as! NSTableView
    let indexes = myTableViewFromNotification.selectedRowIndexes
    // we iterate over the indexes using `.indexGreaterThanIndex`
    var index = indexes.firstIndex
    while index != NSNotFound {
        mySelectedRows.append(index)
        index = indexes.indexGreaterThanIndex(index)
    }
    print(mySelectedRows)
}

答案 1 :(得分:0)

使用-selectedRowIndexes

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSTableView_Class/#//apple_ref/occ/instp/NSTableView/selectedRowIndexes

然后您可以使用这些索引从dataSource中获取数据 (通常是数组)

相关问题