我有一个NSTableView(基于视图)谁从NSarrayController显示信息。所有连接均由IB制成。一切正常,但蓝色选择颜色看起来不符合我的设计理念,所以我想用我自己的颜色改变这种颜色,但直到现在我都失败了。
class MyTable: NSTableView, NSTableViewDelegate {
override func drawBackgroundInClipRect(clipRect: NSRect) {
if self.isRowSelected( self.selectedRow ){
//NSColor.brownColor().colorWithAlphaComponent(0.9).setFill()
// NSBezierPath.fillRect(clipRect)
println("selected")
}
}
}
我真正的问题是:我不知道我应该从哪里开始,子类,NSTableView,NSTableCellView等。
最近我发现了一个方法来说明我应该继承NSTableRowView,并覆盖drawSelectionInRect函数。我已经这样做了,但在IB中我没有NSTableRowView对象。
谢谢。
我这样做了。第一个子类NSTableRowView如你所说:
class MyRowView: NSTableRowView {
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
if selected == true {
NSColor.greenColor().set()
NSRectFill(dirtyRect)
}
}
}
然后只需添加此方法:
func tableView(tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
let myCustomView = MyRowView()
return myCustomView
}
如果我没记错的话,应该这样做。
编辑:我只是尝试我的例子,它的工作原理。在IB中,我将tableview的委托和数据源设置为ViewController,并将我唯一的列命名为“name”。这是我的整个ViewController类:
class ViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
var persons = [Person]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
populate()
}
func populate() {
var first = Person(name: "John")
var second = Person(name: "Jesse Pinkman")
persons = [first, second]
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return persons.count
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
if tableColumn?.identifier == "name" {
let view = tableView.makeViewWithIdentifier(tableColumn!.identifier!, owner: self) as! NSTableCellView
view.textField?.stringValue = persons[row].name
return view
}
return nil
}
func tableView(tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
let myCustomView = MyRowView()
return myCustomView
}
}
首选方法是覆盖drawSelection(in:),draw(_:)
的默认实现是在需要绘制所选行的选择时调用的。您不必自己检查选择状态。
override func drawSelection(in dirtyRect: NSRect) {
NSColor.green.setFill()
dirtyRect.fill()
}
但是,如果您也覆盖draw(in:)
并且不调用超类实现,则必须手动调用drawSelection(in:)
并自行确定选择状态。重写drawSelection(in:)
的另一个好处是“如果选择是动画输入或输出,选择将自动进行alpha混合。”
Swift 4版@Prontto的优秀答案。
class MyRowView: NSTableRowView {
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
if isSelected == true {
NSColor.green.set()
dirtyRect.fill()
}
}
}
.
// In your NSTableViewDelegate
func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? {
return MyRowView()
}