Reputation: 21
I start to be crazy for a simple thing I cannot do: display the tabeview Header . I am using Swift 3.0 with a Dynamic Table View. In this tableview I am creating a contact directory where the user can add a list of contact. I declare my tableview in the storyboard with Dynamic Prototype content. Programmatically I do what I need to do to have my list of contacts and my list is displaying properly in my table view.
Then I declare 1 section and the using the following method:
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50.0
}
In the header I add a button to do some actions on my contact list:
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let frame: CGRect = tableView.frame
let DoneBut: UIButton = UIButton(frame: CGRect(x: frame.size.width - 200, y: 0, width: 150, height: 50))
DoneBut.setTitle("Done", for: .normal)
DoneBut.backgroundColor = UIColor.red
DoneBut.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
DoneBut.backgroundColor = UIColor.blue
let headerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
headerView.backgroundColor = UIColor.red
headerView.addSubview(DoneBut)
return headerView
}
=> Result is no Header displayed only my list. Any advices to be able to the Header ?
Upvotes: 1
Views: 1773
Reputation: 850
You need to amend your heightForHeaderInSection
and viewForHeaderInSection
methods slightly.
You have to add an override for both and also an '_' after the first parenthesis for both methods. (see below)
With this code the section headers displayed for me.
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 50.0
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let frame: CGRect = tableView.frame
let DoneBut: UIButton = UIButton(frame: CGRect(x: frame.size.width - 200, y: 0, width: 150, height: 50))
DoneBut.setTitle("Done", for: .normal)
DoneBut.backgroundColor = UIColor.red
DoneBut.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
DoneBut.backgroundColor = UIColor.blue
let headerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: 50))
headerView.backgroundColor = UIColor.red
headerView.addSubview(DoneBut)
return headerView
}
Upvotes: 1