Last active
February 8, 2018 13:55
-
-
Save szotp/2ba3c8e2b61b3d13a34f71a024ab67ba to your computer and use it in GitHub Desktop.
Example of simple UITableViewDataSource with configurable sections
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
import UIKit | |
protocol ModelProtocol { | |
} | |
class ModelA: ModelProtocol { | |
} | |
class ModelB: ModelProtocol { | |
} | |
protocol CellProtocol { | |
func setup(model: ModelProtocol) | |
} | |
protocol CellProtocolTyped: CellProtocol { | |
associatedtype Model: ModelProtocol | |
func configure(model: Model) | |
} | |
extension CellProtocolTyped { | |
func setup(model: ModelProtocol) { | |
if let model = model as? Model { | |
configure(model: model) | |
} | |
} | |
} | |
class CellA: UITableViewCell, CellProtocolTyped { | |
func configure(model: ModelA) { | |
} | |
} | |
class CellB: UITableViewCell, CellProtocolTyped { | |
func configure(model: ModelB) { | |
} | |
} | |
class SectionsExample: UIViewController, UITableViewDataSource { | |
struct Section { | |
var title = "" | |
var items: [ModelProtocol] = [] | |
} | |
var sections: [Section] = [] | |
override func viewWillAppear(_ animated: Bool) { | |
super.viewWillAppear(animated) | |
sections = [ | |
Section(title: "a", items: [ModelA(), ModelA()]), | |
Section(title: "a", items: [ModelA(), ModelB()]) | |
] | |
let shouldShowLastSection = true | |
if shouldShowLastSection { | |
sections.append(Section(title: "last", items: [])) | |
} | |
} | |
func numberOfSections(in tableView: UITableView) -> Int { | |
return sections.count | |
} | |
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { | |
let sectionModel = sections[section] | |
return sectionModel.title | |
} | |
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
let sectionModel = sections[section] | |
return sectionModel.items.count | |
} | |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let model = sections[indexPath.section].items[indexPath.row] | |
let identifier = "\(type(of: model))" | |
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) | |
if let cellProtocol = cell as? CellProtocol { | |
cellProtocol.setup(model: model) | |
} | |
return cell | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment