我知道我需要实现标题中提到的委托方法;但是我不确定如何做到这一点.
文件说:
You can use the delegate method tableView:rowViewForRow: to customize
row views. You typically use Interface Builder to design and lay out
NSTableRowView prototype rows within the table. As with prototype
cells,prototype rows are retrieved programmatically at runtime.
Implementation of NSTableRowView subclasses is entirely optional.
但是,与单元格不同,界面构建器中没有NSTableRowView类,也不清楚如何设置“原型”行视图.
我正在尝试这样的事情(Swift 3):
func tableView(_ tableView: NSTableView,rowViewForRow row: Int) -> NSTableRowView? { if (row % 4) == 0 { // .................................................. // [ A ] SPECIAL ROW: if let rowView = tableView.make(withIdentifier: "SpecialRow",owner: self) as? NSTableRowView { rowView.backgroundColor = NSColor.gray() return rowView } else { return nil } // ^ Always returns nil (Because I don't know how // to setup the prototype in Interface Builder) } else{ // .................................................. // [ B ] NORMAL ROW (No customization needed) return nil } }
我有类似的代码用于单元格-i.e.,– tableView:viewForTableColumn:row:.
解决方法
>在Interface Builder上,将普通的NSView拖放到表中(它只接受特定列中的drop,而不是表视图的直接子项).
>转到刚刚删除的视图的Identity Inspector,并将其Class更改为“NSTableRowView”.
>因为只在我的代码中设置.backgroundColor属性不起作用,我改为使用this solution并添加了一个框视图作为子视图,并在Interface Builder中进行了配置.我必须在框和行视图之间设置自动布局约束,以便它在运行时延伸到行视图的实际大小.
(或者,我可以使用行视图的wantsLayer属性…)
更新:事实证明我在我的代码中使用的backgroundColor属性是在NSTableRowView中定义的(NSView没有这样的属性,与UIView不同).
但它也会被表视图的设置覆盖(即交替行或不交替),所以我应该在这个方法中自定义它:
func tableView(_ tableView: NSTableView,didAdd rowView: NSTableRowView,forRow row: Int) { if (row % 4) == 0 { rowView.backgroundColor = NSColor.controlAlternatingRowBackgroundColors()[1] } else{ rowView.backgroundColor = NSColor.clear() } }
… …添加后(以及由表视图配置的背景颜色).