Last active
August 23, 2016 06:49
-
-
Save Fogggy/7a413dec0fd833be8b299ddcdddd47c2 to your computer and use it in GitHub Desktop.
UITableView. Add header to table section programmatically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ViewController: UITableViewController { | |
let headerId = "headerId" | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
// Do any additional setup after loading the view, typically from a nib. | |
tableView.sectionHeaderHeight = 50 | |
tableView.registerClass(MyTableHeader.self, forHeaderFooterViewReuseIdentifier: headerId) | |
} | |
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { | |
return tableView.dequeueReusableHeaderFooterViewWithIdentifier(headerId) | |
} | |
} | |
class MyTableHeader: UITableViewHeaderFooterView { | |
let headerLabel: UILabel = { | |
let label = UILabel() | |
label.text = "Section" | |
label.textAlignment = NSTextAlignment.Center | |
label.translatesAutoresizingMaskIntoConstraints = false | |
return label | |
}() | |
override init(reuseIdentifier: String?) { | |
super.init(reuseIdentifier: reuseIdentifier) | |
setupViews() | |
} | |
required init?(coder aDecoder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
func setupViews() { | |
addSubview(headerLabel) | |
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": headerLabel])) | |
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": headerLabel])) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment