There are two ways you can add custom tableview section headers:
In both cases 2 delegate methods must be implemented:
(Xcode 8, Swift 3.0)
- Build a view in code
- Dequeue a prototype cell from the storyboard
In both cases 2 delegate methods must be implemented:
- viewForHeaderInSection
- heightForHeaderInSection
Building a View in Code
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
view.backgroundColor = UIColor.orange
let image = UIImageView(image: sectionImages[section])
image.frame = CGRect(x: 5, y: 5, width: 35, height: 35)
view.addSubview(image)
let label = UILabel()
label.text = sectionTitles[section]
label.frame = CGRect(x: 45, y: 5, width: 100, height: 35)
view.addSubview(label)
return view
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 60
}
Dequeuing a Prototype Cell
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! HeaderCell
cell.headerImage.image = sectionImages[section]
cell.headerLabel.text = sectionTitles[section]
return cell
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section {
case 0,2:
return 45
default:
return 60
}
}
(Xcode 8, Swift 3.0)
thanks !
ReplyDelete