0

I'm setting a header for a UITableView's sections and everything works perfectly :

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

The header of every section is blue, as I expect it to be.

Now, I'd like to change this color when my UITableView is scrolling so I implemented this method in a UITableView extension :

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

When I call this method, header.backgroundColor = color gets called but the background color of the header doesn't change.

So my questions are :

  • is the instance of UIView returned by tableView:viewForHeaderInSection: the same as the actual UIView displayed on the header ? Is it a copy ? Is it something else ?

  • how could I change this header view dynamically ? Do I have to call reloadData just to change my header's background color ? That would be a waste of resources..

Randy
  • 4,335
  • 3
  • 30
  • 64

1 Answers1

0

I think that your problem is related to not reuse of view, so your view constantly is created here

let headerView = MyCustomHeaderView()

and returned, always with blue background color

I hope this helps you

Reinier Melian
  • 20,519
  • 3
  • 38
  • 55
  • Thanks Reinier, but there's no reusability mechanism for header views unfortunately ( http://stackoverflow.com/a/960157/3844377 ) – Randy Jul 07 '16 at 21:56
  • Yes but then how you can do this?, If I found some decent way I will post my results – Reinier Melian Jul 07 '16 at 21:59
  • Alright thanks, for now I'm using `reloadData`, it doesn't impact the performances of my app but I just don'te really like to do unnecessary stuff :) – Randy Jul 07 '16 at 22:39