Reputation: 5441
I currently have some custom section header views used in a UITableView. The views appear when the UITableView is loaded but disappears when scrolling. I saw this post but it seems outdated: tableView section headers disappear SWIFT Here is my code for the header view:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
switch section {
case 0: break
default:
view.backgroundColor = UIColor.clear
let image = UIImageView(image:"Line")
image.frame = CGRect(x: 8, y: 35, width: 340, height: 1)
view.addSubview(image)
let label = UILabel()
let sectionText = self.sectionTitles[section]
label.text = sectionText
label.textColor = UIColor.white
label.font = UIFont(name:"Helvetica Neue" , size: 17)
label.frame = CGRect(x: 10, y: 8, width: 200, height: 20)
view.addSubview(label)
}
return view
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
let headerHeight: CGFloat
switch section {
case 0:
// hide the first section header
headerHeight = CGFloat.leastNonzeroMagnitude
default:
headerHeight = 40
}
return headerHeight
}
Upvotes: 3
Views: 10510
Reputation: 187
The headers only remain fixed when the UITableViewStyle property of the table is set to UITableViewStylePlain. If you have it set to UITableViewStyleGrouped, the headers will scroll up with the cells.
So if you want to fix headers that will stick on the top than you need to set UITableViewStyle to UITableViewStylePlain
if you want to scroll up with the cells than you need to set UITableViewStyle to UITableViewStyleGrouped
Upvotes: 4