Created
February 18, 2019 21:20
-
-
Save reeichert/a4d5e5fc558d83751c21cc3967f2da8b to your computer and use it in GitHub Desktop.
Extension that make easier to add UIView or UIViewController as Header of UITableView
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
// | |
// UITableView+.swift | |
// | |
// Created by Joao Reichert on 18/02/19. | |
// Copyright © 2019 Reichert. All rights reserved. | |
// | |
import UIKit | |
extension UITableView { | |
/// Add Header from View with Auto Layout | |
func addHeader(from view: UIView) { | |
let container = UIView() | |
container.translatesAutoresizingMaskIntoConstraints = false | |
container.sv(view) | |
view.snp.makeConstraints { (make) in | |
make.edges.equalTo(container) | |
} | |
self.tableHeaderView = container | |
container.snp.makeConstraints { (make) in | |
make.centerX.equalTo(self.snp.centerX) | |
make.width.equalTo(self.snp.width) | |
make.top.equalTo(self.snp.top) | |
} | |
self.tableHeaderView?.layoutIfNeeded() | |
let temp = self.tableHeaderView | |
self.tableHeaderView = temp | |
} | |
/// Add new header do UITableView from viewController | |
func addHeader(from headerViewController: UIViewController, inside viewController: UIViewController) { | |
viewController.add(headerViewController) | |
self.addHeader(from: headerViewController.view) | |
} | |
/* | |
To update the header frame on device rotation | |
update layout in viewWillTransitionToSize, but do it in the next draw loop (by wrapping with Dispatch.main.async), since layoutIfNeed() needs to know the correct parent frame first: | |
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { | |
super.viewWillTransition(to: size, with: coordinator) | |
DispatchQueue.main.async { | |
self.tableView.tableHeaderView?.layoutIfNeeded() | |
self.tableView.tableHeaderView = self.tableView.tableHeaderView | |
} | |
} | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment