Isaiah
Isaiah

Reputation: 1892

Swift & NSTableView - Simply select a row

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!

Upvotes: 6

Views: 6482

Answers (3)

Charlton Provatas
Charlton Provatas

Reputation: 2274

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)

Upvotes: 6

curt
curt

Reputation: 4582

@Isaiah answer in Swift 3.0:

.selectRowIndexes(NSIndexSet(index: 0) as IndexSet, byExtendingSelection: false)

Upvotes: 9

Isaiah
Isaiah

Reputation: 1892

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.

Upvotes: 7

Related Questions