0

我有一个用 Swift3 构建的应用程序,带有一个表格视图。我使用情节提要,并且 tableview 放置在视图控制器内。我正在使用部分并通过代码设置部分标题。我希望部分标题显示我为表格视图设置的相同灰色背景。我尝试设置相同的颜色代码,但没有帮助。所以我尝试设置为 UIColor.clear,但它显示为节标题的白色背景。我需要它来使用 tableview 背景。你能指导我出什么问题吗?

代码:

    func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
        print("willDisplayFooterView.. for section \(section) ")
        (view as! UITableViewHeaderFooterView).backgroundView?.backgroundColor = UIColor.clear //UIColor(red: 232.0, green: 232.0, blue: 232, alpha: 1.0) 
    }

    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        print("willDisplayHeaderView,... for section \(section) ")
        (view as! UITableViewHeaderFooterView).backgroundView?.backgroundColor = UIColor.clear //UIColor(red: 232.0, green: 232.0, blue: 232, alpha: 1.0) 
    }

    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

        print("titleForHeaderInSection")
        return self.section [section ]
    }

我尝试使用 viewForHeaderInSection,但它根本没有被调用。

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        print("in viewForHeaderInSection")
        let view = UIView() 
        let label = UILabel()

        label.text = self.section [section ]            
        view.addSubview(label)
        view.backgroundColor = UIColor.clear

        label.translatesAutoresizingMaskIntoConstraints = false

        let horizontallayoutContraints = NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0)
        view.addConstraint(horizontallayoutContraints)

        let verticalLayoutContraint = NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0)
        view.addConstraint(verticalLayoutContraint)

        return view
    }
4

2 回答 2

1

尝试设置视图的背景颜色..而不是 view.backgroundView

func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
        print("willDisplayFooterView.. for section \(section) ")
        (view as! UITableViewHeaderFooterView).backgroundColor = UIColor.clear //UIColor(red: 232.0, green: 232.0, blue: 232, alpha: 1.0) 
    }

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        print("willDisplayHeaderView,... for section \(section) ")
        (view as! UITableViewHeaderFooterView).backgroundColor = UIColor.clear //UIColor(red: 232.0, green: 232.0, blue: 232, alpha: 1.0) 
    }

免责声明:我不太擅长快速语法。但希望这能回答你的问题。

于 2017-08-02T21:03:25.253 回答
1

您可以更改 contentView 的背景颜色而不是 backgroundView

(view as! UITableViewHeaderFooterView).contentView?.backgroundColor = UIColor. groupTableViewBackground
于 2017-08-02T21:36:39.383 回答