I need to add custom header to my table
I try this
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 18)) let label = UILabel(frame: CGRect(x: 20, y: 20, width: 50, height: 50)) label.text = "TEST TEXT" label.textColor = UIColor.whiteColor() self.view.addSubview(view) return view }
but this doesn't work, I see nothing on table
What am I doing wrong ? Or maybe there is another ways ?
There are two main base ways to populate a tableview. The more popular is through Interface Building, using a prototype cell UI object. The other is strictly through code when you don't need a prototype cell from Interface Builder.
If you need to make the footer view fixed at the bottom then you can not use a TableViewController . You will have to use UIViewController , put your tableView as a subview. Put the footer also as another subview and its done.
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 🎉 🎉 🎉
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With