Bartłomiej Semańczyk Bartłomiej Semańczyk - 4 years ago 147
Swift Question

Unexpected Header View in UITableView's section using NSFetchedResultsController

enter image description here

It is easy to see, that the lightblue is a

UITableViewHeaderFooterView
, and the white one is
UITableViewCell
. I use
NSFetchedResultsController
to load sections and groups from CoreData. Every blue header is a new section.

SOMETIMES (not always) there is a header view instead of a table view cell. Why?

In
viewDidLoad
i register header View:

tableView.registerNib(UINib(nibName: "PBOUserWorkDayHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: PBOUserWorkDayHeaderViewIdentifier)


What is more interesting, when I Debug View Hierarchy you can see, that there is my custom cell, just covered by header. Why?

enter image description here

Is it iOS bug? What do you think? Sth wrong with rendering or with my way of thinking?

Answer Source

Since it is a problem with headers, I created a custom method to remove unnecessary headers every time when tableView ask for `viewForHeaderInSection:.

Assuming that you know how to distinguish the headers from other views (in my case they have a custom class) and that you know that header views are direct subviews of tableView you can remove them in following way:

private func removeDoubledHeaders() {
    let subviews = tableView.subviews.reverse()

    var dates = [String]()
    for view in subviews {
        if let header = view as? PBOUserWorkDayHeaderView {
            if let date = header.dateLabel.text {
                if contains(dates, date) {
                    view.removeFromSuperview()
                } else {
                    dates.append(date)
                }
            }
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download