2016-12-27 95 views
0

我實際上使用表視圖來顯示一些數據,我重寫willDisplayHeaderView爲標題添加自定義樣式。除了我無法更改標題標題的背景顏色外,所有工作都很好。這裏是我的代碼:如何使透明標題標題的tableview恩Swift ios

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) 
{ 
    view.backgroundColor = UIColor.clear 
    let title = UILabel() 
    title.font = UIFont(name: "System", size: 22) 
    title.textColor = UIColor(rgba: "#BA0B23") 
    title.backgroundColor = UIColor.clear 

    let header = view as! UITableViewHeaderFooterView 
    header.textLabel?.font=title.font 
    header.backgroundColor = UIColor.clear 
    header.textLabel?.textColor=title.textColor 
    header.textLabel?.textAlignment = NSTextAlignment.center 
    let sepFrame = CGRect(x: 0, y: header.frame.size.height-1, width: header.frame.size.width, height: 1) 
    let seperatorView = UIView(frame: sepFrame) 
    seperatorView.backgroundColor = UIColor(rgba: "#BA0B23") 
    header.addSubview(seperatorView) 
} 

我不知道我做錯了什麼,一些幫助將不勝感激。謝謝

回答

1

我想你應該專注於使用viewForHeaderInSection,而不是willDisplayHeaderView。 這是我會怎麼做:

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { 
    return 110; 
} 

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { 
    headerView.backgroundColor = UIColor.clearColor() 

    let title = UILabel() 
    title.font = UIFont(name: "System", size: 22) 
    title.textColor = UIColor(rgba: "#BA0B23") 
    title.backgroundColor = UIColor.clear 

    headerView.textLabel?.font = title.font 
    headerView.backgroundColor = UIColor.clear 
    headerView.textLabel?.textColor = title.textColor 
    headerView.textLabel?.textAlignment = NSTextAlignment.center 
    headerView.addsubView(title) 

    return headerView; 
} 

希望幫助

+0

如何獲得'headerView'? – Snoobie

0

在故事板,你可以採取一個表格視圖單元格,給予其定製tableViewCell類,然後自定義您的電池根據設計,然後在視圖控制器,你可以返回像這樣的單元格

public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{ 
      let cell:CustomHeaderTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "header") as! CustomHeaderTableViewCell 
      let title = uniqueOrders.arrOrders[section] as? String 
      cell.lblHeaderTitle.text = "Order Id-\(title!)" 
      return cell 
     } 


func numberOfSections(in tableView: UITableView) -> Int{ 
     return uniqueOrders.arrOrders.count 
    } 

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

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
     return "Order Id- \(uniqueOrders.arrOrders[section])" 
    } 
+0

您如何在這裏獲得uitableview標題標題的透明背景? – Snoobie

+0

你可以在故事板文件中做到這一點....在你的標題視圖單元格中,你可以用一個標籤來顯示標題標題並將其背景顏色設置爲你選擇的顏色。 – rohit

+0

要在代碼中設置標題,您可以製作標籤的出口並像這樣設置 - cell.lblHeaderTitle.text =「Order Id - \(title!)」。如我的答案所示 – rohit