【问题标题】:How does tableView:viewForHeaderInSection: works exactly and how to customize this view dynamicallytableView:viewForHeaderInSection: 如何准确工作以及如何动态自定义此视图
【发布时间】:2016-07-07 20:35:43
【问题描述】:

我正在为 UITableView 的部分设置标题,一切正常:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
    let headerView = MyCustomHeaderView()
    headerView.backgroundColor = UIColor.blueColor()
    return headerView
}

每个部分的标题都是蓝色的,正如我所期望的那样。

现在,我想在 UITableView 滚动时更改此颜色,因此我在 UITableView 扩展中实现了此方法:

extension UITableView
{
    func setHeadersColor(color: UIColor)
    {
        guard let delegate = self.delegate
            else {return}
        guard delegate.respondsToSelector(#selector(UITableViewDelegate.tableView(_:viewForHeaderInSection:)))
            else {return}

        for i in 0...self.numberOfSections
        {
            if let header = delegate.tableView!(self, viewForHeaderInSection: i) as? MyCustomHeaderView
            {
                header.backgroundColor = color
            }
        }
    }
}

当我调用此方法时,header.backgroundColor = color 会被调用,但标题的背景颜色不会改变。

所以我的问题是:

  • tableView:viewForHeaderInSection: 返回的UIView 的实例是否与标题上显示的实际UIView 相同?是副本吗?是别的吗?

  • 如何动态更改此标题视图?我是否必须致电reloadData 才能更改标题的背景颜色?那会浪费资源..

【问题讨论】:

  • 您可以使用tableView.headerViewForSection(x)获取表中的视图
  • 我也试过了,但我得到了同样的结果

标签: ios uitableview cocoa-touch


【解决方案1】:

我认为您的问题与未重用视图有关,因此您的视图不断在这里创建

let headerView = MyCustomHeaderView()

然后返回,始终使用蓝色背景色

希望对你有帮助

【讨论】:

  • 感谢 Reinier,但遗憾的是,标题视图没有可重用机制 (stackoverflow.com/a/960157/3844377)
  • 是的,但是你怎么能做到这一点?,如果我找到了一些不错的方法,我会发布我的结果
  • 好的,谢谢,现在我正在使用reloadData,它不会影响我的应用程序的性能,但我真的不喜欢做不必要的事情:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-11
  • 2013-03-25
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-25
相关资源
最近更新 更多