Jack Gal Jack Gal - 1 year ago 174
Swift Question

Setting tableView header's height in Swift

I am trying to set the height of a view that is on top of my prototype cell in a table view controller. I use IB to set it's height (size inspector) and set it to 61 like so (the green view is the 'header' view):

header view

But whenever I run the app, its' height ends up being

. I have an IBOutlet called
for the view in my table view controller, and I do:
println("testUIView Height->\(testUIView.frame.height)")
and indeed ends up being
at runtime.

Here is a screenshot showing its' height at runtime:

enter image description here

So my question is: How can I set the view's height so it is 61 at runtime so it indeed looks like my first screenshot (size-wise)?

I tried to set its' height property inside
override func viewWillLayoutSubviews()
but it did not let me assign a value to the height
testUIView.frame.height = CGFloat(61.0)

Any help is appreciated! Thanks in advance!


Answer Source

If you'd like to use a header for you UITableView instead you can design another prototype cell in Interface Builder, make a custom class based on a UITableViewCell and assign it to the prototype cell in interface builder on the class inspector.

Then in your controller you're going to use

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?

In that function you're actually going to create a reusable cell from your table view but cast as the custom cell you made for the header. You will have access to all of it's properties like a regular UITableViewCell, then you're just going to return the cell's view

return cell.contentView

Another method you're going to use is

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 61.0

That one is pretty self explanatory.

Swift 3.0

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 61.0    
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download