【问题标题】:How Can I Change Background Color and Text Color of UITableHeaderView如何更改 UITableHeaderView 的背景颜色和文本颜色
【发布时间】:2019-10-10 15:27:04
【问题描述】:

我知道如何提供自定义 UITableview 标头以及如何自定义它。但是我在使用带有 SectionTitles 的 UITableview 时被卡住了。

如何更改 UITableview 标题的背景颜色以及如何更改 UITableview 标题的文本颜色。

Requirment illustration can be found here.

【问题讨论】:

  • 这是在文档中。检查 UITableViewDelegate 文档 re: header view.
  • 我认为您的意思是 SectionHeaderView,而不是 tableheaderview,对吧?
  • @Chris 是的,SectionHeaderView。

标签: ios swift uitableview uitableviewsectionheader


【解决方案1】:

您可以使用以下方法为您的标题创建 customView: 我制作了一个示例视图供您自定义。

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

        let headerView = UIView()
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = UIColor.white
        label.numberOfLines = 0
        label.textAlignment = .center
        label.font = .boldSystemFont(ofSize: 20)
        headerView.addSubview (questionLabel)
        headerView.backgroundColor = .blue
        NSLayoutConstraint.activate([
            questionLabel.centerYAnchor.constraint(equalTo: headerView.centerYAnchor, constant: 0),
            questionLabel.leadingAnchor.constraint(equalTo: headerView.leadingAnchor, constant: 0),
            questionLabel.trailingAnchor.constraint(equalTo: headerView.trailingAnchor, constant: 0)
            ])

        return headerView

    }

【讨论】:

  • 此解决方案可用于添加自定义节标题。当你使用 UITableviewDataSource 的func sectionIndexTitles(for tableView: UITableView) -> [String]? { return [sectionTitles] } 显示索引时,它不能用于自定义默认部分。
  • 如果您的标题有一组标题,您可以这样做:即 label.text = sectionTitles[section]
【解决方案2】:

我找到了解决方案。 UITableViewDelegate这个方法可以用来自定义默认的section header。

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        view.tintColor = .red

        if let header = view as? UITableViewHeaderFooterView {
            header.textLabel?.textColor = .white
        }
    }

【讨论】:

    猜你喜欢
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    相关资源
    最近更新 更多