Skip to content

Instantly share code, notes, and snippets.

@JohnCoates
Created June 19, 2017 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JohnCoates/46fcb59fcf79392f0c8b731ec1b77cbc to your computer and use it in GitHub Desktop.
Save JohnCoates/46fcb59fcf79392f0c8b731ec1b77cbc to your computer and use it in GitHub Desktop.
UITableView typed cells
extension UITableView {
func registerCell<CellType: UITableViewCell>(type: CellType.Type) {
register(type, forCellReuseIdentifier: String(describing: type))
}
func dequeueReusableCell<CellType: UITableViewCell>(for indexPath: IndexPath) -> CellType {
let identifier = String(describing: CellType.self)
let untypedCell = dequeueReusableCell(withIdentifier: identifier, for: indexPath)
guard let cell = untypedCell as? CellType else {
let error = "Couldn't cast cell \(untypedCell) " +
"with identifier \(identifier) as \(CellType.self)"
fatalError(error)
}
return cell
}
}
@JohnCoates
Copy link
Author

Usage:

func setUpTableView() {
    tableView.registerCell(type: EditKitLinkCell.self)
    ...
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: EditKitLinkCell = tableView.dequeueReusableCell(for: indexPath)
    ...
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment