Skip to content

Instantly share code, notes, and snippets.

@jlalvarez18
Last active August 29, 2015 14:24
Show Gist options
  • Save jlalvarez18/123f9827a0e7f75a8e08 to your computer and use it in GitHub Desktop.
Save jlalvarez18/123f9827a0e7f75a8e08 to your computer and use it in GitHub Desktop.
Swift Dynamic UITableView Header View
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
self.layoutHeaderView(size.width)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.layoutHeaderView(self.tableView.bounds.width)
}
func layoutTableHeaderView(width: CGFloat) {
let view = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 0))
view.setTranslatesAutoresizingMaskIntoConstraints(false)
// [add subviews and their constraints to view]
let widthConstraint = NSLayoutConstraint(item: view, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: width)
view.addConstraint(widthConstraint)
let height = view.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
view.removeConstraint(constraint)
view.frame = CGRect(x: 0, y: 0, width: width, height: height)
view.setTranslatesAutoresizingMaskIntoConstraints(true)
self.tableView.tableHeaderView = view
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment