sudhanshu-shishodia
sudhanshu-shishodia

Reputation: 1108

UITableView header hides on beginUpdates() in Swift

I have a UITableView in a controller where I'm setting its tableHeaderView property in viewDidLoad()

let headerView = tableView.dequeueReusableCellWithIdentifier("HeaderView") as! HeaderView
tableView.tableHeaderView = headerView

All works well, until I call tableView.beginUpdates()/tableView.endUpdates() OR tableView.reloadData(). Header space is still there, but content goes blank.

What am I doing wrong ? Please suggest.

Upvotes: 1

Views: 824

Answers (1)

oyalhi
oyalhi

Reputation: 3994

== EDITED OCT 12, 2016 ==

You should not dequeue the header view. Instead have a view property and assign that view to be the headerview for your tableview:

class SomeViewController: UIViewController {
    // MARK: - Outlets
    @IBOutlet var tableView: UITableView!

    // MARK: - Properties
    var headerView: UIView!

    // MARK: - Lifecycle Methods
    override func viewDidLoad() {
        super.viewDidLoad()
        headerView = HeaderView()
        tableView.headerView = headerView
    }
}

== ORIGINAL ANSWER - DOES NOT ADDRESS THE QUESTION ==

You should not put the headerview on viewDidLoad. Instead create and return the header in the delegate (below code assumes you have one section).

IMPORTANT: You need to call dequeueReusableHeaderFooterViewWithIdentifier NOT dequeueReusableCellWithIdentifier

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier("HeaderView") as! HeaderView
    return headerView   
}

Upvotes: 1

Related Questions