Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - how to make custom header for UITableView?

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 ?

like image 717
Alexey K Avatar asked Aug 12 '15 12:08

Alexey K


People also ask

How do I populate UITableView?

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.

How can I make the Footerview always stay at the bottom in Uitableviewcontroller?

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.


2 Answers

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 🎉 🎉 🎉Check it here in image

like image 184
Mohit G. Avatar answered Sep 18 '22 08:09

Mohit G.


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.

like image 20
Tanguy G. Avatar answered Sep 19 '22 08:09

Tanguy G.