如何透明tableview en swift ios的标题标题

时间:2016-12-27 20:46:23

标签: ios uitableview swift3 xcode8

我实际上是使用表格视图来显示某些数据而我正在覆盖willDisplayHeaderView以为标题添加自定义样式。一切正常,但我不能改变标题标题的背景颜色。这是我的代码:

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)
}

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

2 个答案:

答案 0 :(得分:2)

在故事板中,您可以获取表格视图单元格,给它自定义的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])"
    }

答案 1 :(得分: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;
}

希望有所帮助