Swift & NSTableView - Simply select a row

2019-04-10 13:33发布

I'd like to programatically select a row in my NSTableView, with just one column.

func selectColumnIndexes(_ indexes: NSIndexSet!,
    byExtendingSelection extend: Bool)

I have been playing around with this, but I am not sure how to write "Select row #2".
Do I have to start with the variable connected to the @IBOutlet of my Table View? I have to indicate it is about my NSTableView somehow.

Thanks!

3条回答
女痞
2楼-- · 2019-04-10 14:15

Okay, I've got it. It turned out to be

@IBOutlet weak var NoteTableView: NSTableView!
NoteTableView.selectRowIndexes(NSIndexSet(index: 0), byExtendingSelection: false)

I couldn't quite figure out the part with NSIndexSet. I was fiddling around with init(), which turned out to be unnecessary.

查看更多
放荡不羁爱自由
3楼-- · 2019-04-10 14:19

Swift 4 Solution

I created an extension to make a little easier to do this. Also if you implemented a click action on the table view cell this will invoke it as well

extension NSTableView {
    func selectRow(at index: Int) {
        selectRowIndexes(.init(integer: index), byExtendingSelection: false)
        if let action = action {
            perform(action)
        }
    }
}

/// USAGE:
NSTableView().selectRow(at: 0)
查看更多
等我变得足够好
4楼-- · 2019-04-10 14:20

@Isaiah answer in Swift 3.0:

.selectRowIndexes(NSIndexSet(index: 0) as IndexSet, byExtendingSelection: false)
查看更多
登录 后发表回答