Напечатайте номер строки NSTableView строки, выбранной пользователем

У меня есть NSTableView с одним столбцом. Я хотел бы напечатать номер строки, по которой щелкнул пользователь. Я не уверен, где я должен начать с этого. Есть ли способ для этого?

2 ответа

Решение

Вы можете использовать selectedRowIndexes свойство из tableView в tableViewSelectionDidChange метод в вашем делегате NSTableView.

В этом примере tableView допускает множественный выбор.

Свифт 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)
}

Использование -selectedRowIndexes

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSTableView_Class/

Затем вы можете использовать эти индексы, чтобы получить данные из вашего dataSource(обычно массив)

Другие вопросы по тегам