-->

NSTableViewCell setSelected?

2019-09-11 11:40发布

问题:

How do I communicate between my NSViewController and the NSTableViewCell when I select that cell on my tableView? On iOS you could use setSelected but in OSX it is totally different. The NSTableCellView class doesn't have any function like that. I might be missing something simple. How do I talk with that cell? I have a custom class cell and on my tableView controller, I got:

func tableView(tableView: NSTableView, shouldSelectRow row: Int) -> Bool {

    let previousSelected = NSIndexSet(index: selectedRow)
    selectedRow = row
    let indset = NSIndexSet(index: row)

    // animate row expansion
    self.tableView.noteHeightOfRowsWithIndexesChanged(indset)

    // animate back the previously selected
    self.tableView.noteHeightOfRowsWithIndexesChanged(previousSelected)
    return true
}

I also have the height of Row...

func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
    if row == selectedRow{
        return 90
    }else{
        return 40
    }
}

What I'm trying to do is to let my cell know it got selected, so it can display different things when selected. Anyone ?

回答1:

Selection doesn't operate on cells, it operates on rows. NSTableRowView has a selected property. It's generally responsible for drawing the selected appearance of table rows with its drawSelectionInRect() method.

How exactly does your cell change its behavior or appearance based on whether it's selected? Are you sure that shouldn't be done by the row, instead? Perhaps you should be using a custom subclass of NSTableRowView.

If you must, you can find the row view from the cell view. One way is to just assume the cell's superview is the row view, which it should be when it's not nil. Another approach is to ask the table view which row the cell is for using rowForView(self) and then ask the table view for the row view using rowViewAtRow(_:makeIfNecessary:).



回答2:

NSTableCellView does not seem to have a selected property. Perhaps you can subclass it and add such property.

Then, implement the delegate method:

optional func tableView(_ tableView: NSTableView,
        shouldSelectRow row: Int) -> Bool

...and in the cases when you return true (i.e., the row should be selected), set the selected property you just defined of the corresponding cell to true.

If you want the cell to do something when selected, define your property like this:

var selected:Bool {
    didSet {
        if selected {
            // Act accordingly...
        }
    }
}