Reputation: 4862
I have a UITableView with section headers. The whole tableview has UITableViewAutomaticDimension set, for both cells as well as headers:
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet var sectionHeader: MyTableViewHeaderFooterView!
let data = [
"Lorem ipsum dolor sit amet",
"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation",
"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 44.0
self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension
self.tableView.estimatedSectionHeaderHeight = 44.0
}
// MARK: - Table View
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
self.sectionHeader.label.text = "Section \(section)"
return self.sectionHeader
} else {
return nil
}
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! MyTableViewCell
cell.label.text = data[indexPath.row]
return cell
}
}
The problem is that I want to hide some section headers. The second section header should be hidden because I return nil instead of a view, however the space is still reserved. Why?
Xcode project on Github: https://github.com/bvankuik/SectionHeaderAlwaysVisible
Upvotes: 1
Views: 900
Reputation: 939
Apple's documentation about UITableViewAutomaticDimension
says:
Returning this value from tableView:heightForHeaderInSection: or tableView:heightForFooterInSection: results in a height that fits the value returned from tableView:titleForHeaderInSection: or tableView:titleForFooterInSection: if the title is not nil.
I'm afraid you need to change the way you calculate the header height with something like this:
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 1 {
return 0
} else {
return UITableViewAutomaticDimension
}
}
Upvotes: 6