如何使透明标题标题的tableview恩Swift ios

问题描述:

我实际上使用表视图来显示一些数据,我重写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) 
} 

我不知道我做错了什么,一些帮助将不胜感激。谢谢

我想你应该专注于使用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

在故事板,你可以采取一个表格视图单元格,给予其定制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