2012-01-18 14 views
1

我有基於視圖的NSTableView與自定義NSTextField子類實例繪製行標籤。表格視圖中的自定義NSTextField:如何知道是否選擇了行來更改背景顏色?

取決於是否選擇了一行(突出顯示)我想更改自定義文本字段的背景顏色。

如果父表格行被選中,我如何知道我的文本字段的drawRect:(NSRect)dirtyRect

文本字段甚至不知道它是表視圖的一部分(並且不應該)。

如果我在表格視圖中放入一個普通的NSTextField,它會根據行選擇狀態自動更改其字體顏色,因此它必須以某種方式可能讓文本字段知道它是被選中/突出顯示還是現在。

回答

0

表視圖是單元格視圖中視圖的父視圖。 因此,您可以在drawRect方法中迭代視圖層次結構以查找父表視圖。 並用它檢查包含自定義NSTextField的行是否被選中。

override public func drawRect(dirtyRect: NSRect) { 
    var backgroundColor = NSColor.controlColor() //Replace by the non selected color 
    var parentView = superview 
    while parentView != nil { 
     if let tableView = parentView as? NSTableView { 
      let row = tableView.rowForView(self) 
      if tableView.isRowSelected(row) { 
       backgroundColor = NSColor.alternateSelectedControlColor() //Replace by the selected background color 
      } 
      break 
     } 
     parentView = parentView?.superview 
    } 
    //Perform the drawing with the backgroundColor 
    // ... 
} 
相關問題