Swift & NSTableView - Simply select a row
Asked Answered
G

3

6

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!

Grandniece answered 12/8, 2014 at 19:35 Comment(0)
A
6

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)
Albumin answered 8/2, 2018 at 23:26 Comment(0)
C
9

@Isaiah answer in Swift 3.0:

.selectRowIndexes(NSIndexSet(index: 0) as IndexSet, byExtendingSelection: false)
Chili answered 24/12, 2016 at 5:25 Comment(0)
G
7

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.

Grandniece answered 13/8, 2014 at 18:54 Comment(0)
A
6

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)
Albumin answered 8/2, 2018 at 23:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.