Skip to content

Instantly share code, notes, and snippets.

@lalkrishna
Last active August 5, 2022 05:02
Show Gist options
  • Save lalkrishna/4e2c287a0cf89ce1ac008dfccf4dbf8e to your computer and use it in GitHub Desktop.
Save lalkrishna/4e2c287a0cf89ce1ac008dfccf4dbf8e to your computer and use it in GitHub Desktop.
Tableview Extensions for Making dequeuing easier.
extension UITableView {
func register<T: UITableViewCell>(_ cellClass: T.Type) {
register(T.self, forCellReuseIdentifier: String(describing: T.self))
}
func reusableCell<T: UITableViewCell>(for indexPath: IndexPath) -> T {
// swiftlint:disable force_cast
dequeueReusableCell(withIdentifier: String(describing: T.self), for: indexPath) as! T
}
func reusableHeaderFooterView<T: UITableViewHeaderFooterView>() -> T {
// swiftlint:disable force_cast
dequeueReusableHeaderFooterView(withIdentifier: String(describing: T.self)) as! T
}
}
extension UITableView {
func autoSizeHeaderAndFooter() {
let width = self.bounds.width
let autoSize = { (view: UIView) in
view.translatesAutoresizingMaskIntoConstraints = false
let widthConstraint = NSLayoutConstraint(
item: view,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: width)
view.addConstraint(widthConstraint)
let height = view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
view.removeConstraint(widthConstraint)
view.frame = CGRect(x: 0, y: 0, width: width, height: height)
view.translatesAutoresizingMaskIntoConstraints = true
}
if let view = tableHeaderView {
autoSize(view)
tableHeaderView = view
}
if let view = tableFooterView {
autoSize(view)
tableFooterView = view
}
}
}
extension UIView {
static var identifier: String { String(describing: Self.self) }
static var nib: UINib { UINib(nibName: String(describing: self), bundle: nil) }
}
extension UITableView {
func register<T: UITableViewHeaderFooterView>(_ viewClass: T.Type) {
register(T.nib, forHeaderFooterViewReuseIdentifier: T.identifier)
}
}
// MARK: - Usage
let cell: CustomCellClass = tableView.reusableCell(for: indexPath)
// Register Cell
tableView.register(CustomCellClass.self)
// HeaderFooterView
let header: CustomTableViewHeaderFooterView = tableView.dequeueReusableHeaderFooterView()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment