Skip to content

Instantly share code, notes, and snippets.

@mickspecial
Created January 27, 2019 00:54
Show Gist options
  • Save mickspecial/a09b632cc2f3dfa598fe7e0c4cc14864 to your computer and use it in GitHub Desktop.
Save mickspecial/a09b632cc2f3dfa598fe7e0c4cc14864 to your computer and use it in GitHub Desktop.
Tableview and Cell Helpers
// No Storyboards
// Some reasons why
// https://www.youtube.com/watch?v=bd2KSWLXo3A
// https://www.youtube.com/watch?v=U1Ub-LFIqfA
// https://www.youtube.com/watch?v=g6yz5oX5iWc
// note - was was a huge fan of SB's - but gave this approach a try... never looked back
// Tableview Extensions
extension UITableView {
/// SwifterSwift: Dequeue reusable UITableViewCell using class name for indexPath
///
/// - Parameters:
/// - name: UITableViewCell type.
/// - indexPath: location of cell in tableView.
/// - Returns: UITableViewCell object with associated class name.
public func dequeueReusableCell<T: UITableViewCell>(withClass name: T.Type, for indexPath: IndexPath) -> T {
guard let cell = dequeueReusableCell(withIdentifier: String(describing: name), for: indexPath) as? T else {
fatalError("Couldn't find UITableViewCell for \(String(describing: name))")
}
return cell
}
/// SwifterSwift: Register UITableViewCell using class name
///
/// - Parameter name: UITableViewCell type
public func register<T: UITableViewCell>(cellWithClass name: T.Type) {
register(T.self, forCellReuseIdentifier: String(describing: name))
}
}
// Barebones Custom TVCell
class YourCustomCell: UITableViewCell {
// if you want to use and mod one of the default styles
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: UITableViewCell.CellStyle.subtitle, reuseIdentifier: reuseIdentifier)
setupView()
}
// if you creating from scratch
// override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
// super.init(style: style, reuseIdentifier: reuseIdentifier)
// setupView()
// }
override func layoutSubviews() {
super.layoutSubviews()
}
private func setupView() {
tintColor = .red
selectedBackgroundView = UIView()
backgroundColor = .white
accessoryType = .disclosureIndicator
shouldIndentWhileEditing = true
textLabel?.textColor = .green
textLabel?.font = UIFont.systemFont(ofSize: 20, weight: .bold)
detailTextLabel?.textColor = .orange
detailTextLabel?.font = UIFont.systemFont(ofSize: 14)
}
func fillCell(_ data: YourModel) {
textLabel?.text = data.name
detailTextLabel?.text = data.age
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// Register the cell in your TV controller
yourTableView.register(cellWithClass: YourCustomCell.self)
// Cell for index helper - no need to force cast
let cell = tableView.dequeueReusableCell(withClass: YourCustomCell.self, for: indexPath)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment