2016-11-30 43 views
1

林試圖改變標題行的背景顏色以基於視圖的NSTableView的但不具有任何運氣用於NSTableView的標題

改變背景顏色嘗試這樣做:

tableView.headerView?.layer?.backgroundColor = CGColor.black 

和這個(正如在前一篇Obj-C文章中提出的那樣):

for column in tableView.tableColumns { 
    column.headerCell.backgroundColor = NSColor(red: 0/255, green: 108/255, blue: 178/255, alpha: 1) 
    column.headerCell.textColor = NSColor.blue 
} 

回答

-1

下面是一個小例子。

var Sections = ["SECTION 01","SECTION 02"] 
let items = [["ITEM 01", "ITEM 02"], ["ITEM 03"]] 

    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
      return Sections[section] 
     } 

    func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { 
       let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView 
       header.contentView.backgroundColor = UIColor(red: 0/255, green: 181/255, blue: 229/255, alpha: 1.0) 
       header.textLabel!.textColor = UIColor.whiteColor() 
       header.alpha = 0.5 

     } 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return self.items[section].count 
    } 
+0

謝謝。這個例子是針對iOS/UITableView的。不幸的是,我在macOS中使用了NSTableView。我確實嘗試過'column.headerCell.controlView?.layer?.backgroundColor = CGColor(紅色:0/255,綠色:108/255,藍色:178/255,alpha:1)',但這似乎並不奏效 –

1

創建自定義NSTableHeaderCell子類,並設置NSTableColumnheaderCell屬性允許您自定義表格的標題行的外觀。

Apple的documentation建議在定製標題單元格時覆蓋drawInterior:withFrame方法,但這不會填充整個單元格的背景顏色 - 需要覆蓋draw:withFrame。調用drawInterior將繪製標題的標籤和其他元素。如果要將標題的內容垂直居中在單元格中,則需要調整內部框架。

override func draw(withFrame cellFrame: NSRect, in controlView: NSView) { 
    NSColor.gray.setFill() 
    NSBezierPath.fill(cellFrame) 

    let interiorFrame = CGRect(x: cellFrame.origin.x, y: cellFrame.origin.y + 4.0, width: cellFrame.size.width, height: 14.0) 
    drawInterior(withFrame: interiorFrame, in: controlView) 
} 

有一點需要注意 - 如果您需要,還需要繪製列分隔線。