IanS
IanS

Reputation: 145

Xcode Swift. How to programmatically select Cell in view-based NSTableView

I can click a cell and edit its contents. But, instead of click/selecting a cell is it possible to programmatically select a cell - basically give a cell focus ready for editing.

Somebody here on StackOverflow asked the same question about UITableView and the answer given was:-

let indexPath = NSIndexPath(forRow: 2, inSection: 0)
tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: .Middle)

Does selectRowAtIndexPath select a cell? In any case, my NSTableView doesn't appear to have a .selectRowAtIndexPath(... method anyway.

Please point me at a resource where I can get a start and figure the rest out for myself.

Upvotes: 3

Views: 1793

Answers (3)

Paul Stevenson
Paul Stevenson

Reputation: 145

I find this is pretty clean... as an extension of the cell

extension NSTableViewCell
{
    func select()
    {
        guard let row = self.tableView?.row(for: self) else { return }

        self.tableView?.selectRowIndexes(IndexSet([row]), byExtendingSelection: false)
    }
}

Upvotes: -1

Anshuman Singh
Anshuman Singh

Reputation: 1126

Use can use this , if you just want to highlight the table view cell or row and also performs some operations to it through tableViewSelectionDidChange delegate method of the NSTablView.

mytableView.selectRowIndexes(IndexSet([indexOfTheCellWantToSelect]), byExtendingSelection: true)

Upvotes: -1

IanS
IanS

Reputation: 145

I'd googled this for two days solid before asking the question here. But now almost immediately after posting the question I managed to get it working. In fact it's so simple I can't believe it took so long to figure it out.

// Assuming we want to programmatically select Column 4, Row 5
myTableView?.editColumn(4, row: 5, withEvent: nil, select: true)

On my travels I found dozens of people asking this question but no simple answers. Or answers that actually worked with NSTableView rather than UITableView and when tableView is 'view based' rather than cell based. So I hope me posting this here will help some of those people.

Upvotes: 4

Related Questions