Swift - how to make custom header for UITableView?
The best working Solution of adding Custom header view in UITableView for section in swift 4 is --
#1 first Use method ViewForHeaderInSection as below -
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.width, height: 50))
let label = UILabel()
label.frame = CGRect.init(x: 5, y: 5, width: headerView.frame.width-10, height: headerView.frame.height-10)
label.text = "Notification Times"
label.font = .systemFont(ofSize: 16)
label.textColor = .yellow
headerView.addSubview(label)
return headerView
}
#2 Also Don't forget to set Height of the header using heightForHeaderInSection UITableView method -
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50
}
and you're all set ð ð ð
If you are using custom cell as header, add the following.
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
let headerCell = tableView.dequeueReusableCell(withIdentifier: "customTableCell") as! CustomTableCell
headerView.addSubview(headerCell)
return headerView
}
If you want to have simple view, add the following.
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView:UIView = UIView()
return headerView
}
Did you set the section header height in the viewDidLoad?
self.tableView.sectionHeaderHeight = 70
Plus you should replace
self.view.addSubview(view)
by
view.addSubview(label)
Finally you have to check your frames
let view = UIView(frame: CGRect.zeroRect)
and eventually the desired text color as it seems to be currently white on white.