Reputation: 2366
I'm trying to add a view to my tableview as a tableHeaderView. I drag a view from the interface builder and drop it into my tableview. The size of the header is a small, so I resize it by coding. When I run my app, it becomes like this:
If I change background colour to white colour
If I change background colour to clear idea
Here is the code I change my tableview header size:
self.myTableView.tableHeaderView?.frame = CGRectMake(0, 0, screenWidth, 290)
Any suggestion to fix it please!
Upvotes: 0
Views: 767
Reputation: 13833
Use this UItableView extension.
I was having the same issue
extension UITableView {
func setTableHeaderView(headerView: UIView?) {
// set the headerView
tableHeaderView = headerView
// check if the passed view is nil
guard let headerView = headerView else { return }
// check if the tableHeaderView superview view is nil just to avoid
// to use the force unwrapping later. In case it fail something really
// wrong happened
guard let tableHeaderViewSuperview = tableHeaderView?.superview else {
assertionFailure("This should not be reached!")
return
}
// force updated layout
headerView.setNeedsLayout()
headerView.layoutIfNeeded()
// set tableHeaderView width
tableHeaderViewSuperview.addConstraint(headerView.widthAnchor.constraint(equalTo: tableHeaderViewSuperview.widthAnchor, multiplier: 1.0))
// set tableHeaderView height
let height = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
tableHeaderViewSuperview.addConstraint(headerView.heightAnchor.constraint(equalToConstant: height))
}
}
Upvotes: 2
Reputation: 932
Create a xib which holds the kind of header view
you want to add it on TableView
. Then load your xib in viewWillAppear
method of the controller
using [[NSBundle mainBundle]loadNibNamed:@""]
method. Now add that NSBundle
returned view as tableView
header by using, tv.tableHeaderView = <your UI view>;
Upvotes: 0