问题
I've got a simple example of an app here which I slapped together, and what I'm getting is pretty much what I'm after.
The issue is that when the view loads up, in the NSViewController's viewDidLoad, I set the tableView's selected index to 0 i.e. the first item (which works).
What I do notice is that when this happens, the selected row comes up as grey in color (i.e. as if it's not an active window/view)… It only seems to high light in the normal blue color when I physically click on the row that's selected.
I can confirm that the row is selected and everything appears fine.
Any ideas?
To confirm, the code I use to select the row is:
override func viewDidAppear() {
self.tableView.selectRowIndexes(NSIndexSet(index: 0), byExtendingSelection: false)
}
Here is what's happening with the actual view itself:
ABOVE: The darker grey line is the "selection bar". This is what happens as soon as the view becomes active.
ABOVE: Once I click on that row (the one which was once dark grey), I get he desired high lighting.. i.e. Navy Blue.
回答1:
The reason why the cell is grey is because the table view doesn't have focus / isn't the first responder.
There are 3 states for tableView cell selection color
1) no selection = clear row background
2) selection and focus = blue row background
3) selection and no focus = grey row background
This is probably because another view has focus. Simply selecting a cell doesn't shift focus to a tableView. You need to call NSWindow.makeFirstResponder() to change the focus.
func tableViewSelectionDidChange(notification: NSNotification) {
let tableView = notification.object as! NSTableView
if tableView.selectedRow != -1 {
self.window!.makeFirstResponder(self.tableView)
}
}
回答2:
I've managed to find out what's going on. (I think) and it seems to work.
I had to:
- Subclass
NSTableRowView
- Add a new NSView just below the actual cell view (row) in Interface Builder
- Set the new Row View's class to 'myNSTableViewSubClass'
- Set the row view's Identifier to:
NSTableViewRowViewKey
(this is very specific, and that literally is the key, if this isn't set, it won't work be regarded as the Table Row View. in the subclass I had to override the
emphasised: Bool
to always return yes e.g.:override var emphasized: Bool{ get{ return true } set{ //You need to have the "set" there as it's a mutable prop //It doesn't have to do untying though } }
And voila..
The catch in my case was in 4 above.
来源:https://stackoverflow.com/questions/33894114/nstableview-initial-selection-grey-until-clicked-focussed