user481610
user481610

Reputation: 3270

Correct manner in implementing a tables header view using Swift and UITableView

I'm a junior iOS developer and I'm playing around with a UITableView. As the title suggests, I'm looking for the correct way to insert a given view into the header section of a UITableView. I've used the following two methods:

tableView.tableHeaderView = NSBundle.mainBundle().loadNibNamed("InputToListCell", owner: nil, options: nil)[0] as! UITableViewCell

and

let nib = UINib(nibName: "InputToListCell", bundle: nil)
tableView.registerNib(nib, forHeaderFooterViewReuseIdentifier:"InputToListCell")

override func tableView(tableView:UITableView, viewForHeaderInSection section:NSInteger) -> UIView{
    let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier("InputToListCell")
    return header!;
}

Which would be the better method? If there is even a better method as both of them work or is this a matter of preference? I'm just wondering why have two things that do the same thing? For flexibility?

Upvotes: 0

Views: 147

Answers (1)

David Berry
David Berry

Reputation: 41236

They do different things.

Your first block will add a tableHeaderView A single view that appears over the whole table and scrolls with the table.

The second block will create a section header that will be displayed at the top of each section in the table. It will mostly scroll with the table, but it will pin to the top of the screen until the whole section has been scrolled off screen.

So, it all depends on which you're actually trying to do. In a table without sections (technically with only one section), they are very similar with the difference being that the second will pin to the top of the screen, but the first will not.

BTW, in both cases, the tableHeaderView need not (probably shouldn't be) derived from UITableViewCell

Upvotes: 1

Related Questions