![](/img/trans.png)
[英]How to learn in Swift inside 'tableViewSelectionDidChange:' in which NSTableView the selection did change?
[英]How to change selection color for NSTableView which use NSArrayContoller as content source?
我有一個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中,我將表視圖的委托和數據源設置為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:)
確定選擇狀態。 覆蓋drawSelection(in:)
另一個好處是“如果選擇動畫或不動畫,則選擇將自動進行alpha混合”。
@Prontto的Swift 4版本的絕佳答案。
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()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.