Print the NSTableView's row number of the row clicked by the user

你。 提交于 2019-11-28 03:02:42

问题


I have a NSTableView with one column. I would like to print the row number of the row that the user has clicked on. I am not sure where I should start with this. Is there a method for this?


回答1:


You can use the selectedRowIndexes property from the tableView in the tableViewSelectionDidChange method in your NSTableView delegate.

In this example, the tableView allows multiple selection.

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



回答2:


Use -selectedRowIndexes

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

Then you can use those indexes to grab the data from your dataSource (typically an array)



来源:https://stackoverflow.com/questions/29198210/print-the-nstableviews-row-number-of-the-row-clicked-by-the-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!