Last active
September 3, 2021 15:41
-
-
Save thomsmed/15dce460b8b604e15e47e39a5b756a7f to your computer and use it in GitHub Desktop.
Useful UITableView extensions
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+Extensions.swift | |
// | |
import Foundation | |
import UIKit | |
protocol ReusableCell: AnyObject { | |
static var reuseIdentifier: String { get } | |
} | |
extension ReusableCell { | |
static var reuseIdentifier: String { String(describing: self) } | |
} | |
extension UITableViewCell: ReusableCell {} | |
extension UITableViewHeaderFooterView: ReusableCell {} | |
extension UITableView { | |
func dequeue<T: ReusableCell>(as type: T.Type, identifier: String? = nil) -> T { | |
guard let cell = dequeueReusableCell(withIdentifier: identifier ?? type.reuseIdentifier) as? T else { | |
fatalError("Unable to dequeue \(T.self)") | |
} | |
return cell | |
} | |
func dequeueHeaderFooter<T: ReusableCell>(as type: T.Type, identifier: String? = nil) -> T { | |
guard let headerFooter = dequeueReusableHeaderFooterView(withIdentifier: identifier ?? type.reuseIdentifier) as? T else { | |
fatalError("Unable to dequeue \(T.self)") | |
} | |
return headerFooter | |
} | |
func registerFromNib<T: ReusableCell>(_ type: T.Type) { | |
register(UINib(nibName: type.reuseIdentifier, bundle: nil), forCellReuseIdentifier: type.reuseIdentifier) | |
} | |
func register<T: ReusableCell>(_ type: T.Type) { | |
register(T.self, forCellReuseIdentifier: type.reuseIdentifier) | |
} | |
func registerHeaderFooter<T: ReusableCell>(_ type: T.Type) { | |
register(T.self, forHeaderFooterViewReuseIdentifier: type.reuseIdentifier) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment