Skip to content

Instantly share code, notes, and snippets.

@klundberg
Created August 27, 2015 15:49
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 klundberg/a846779f9a97285d6667 to your computer and use it in GitHub Desktop.
Save klundberg/a846779f9a97285d6667 to your computer and use it in GitHub Desktop.
protocol BaseSection {
var cellIdentifier: String { get }
func numberOfRows() -> Int
func registerIdentifier(tableView: UITableView)
func configureCell(cell: UITableViewCell, indexPath: NSIndexPath)
}
class Section<T, Cell: UITableViewCell>: BaseSection {
var rows: [T] = []
var cellIdentifier = ""
var configure: (Cell, T, NSIndexPath) -> () = { (_, _, _) in }
func registerIdentifier(tableView: UITableView) {
tableView.registerClass(Cell.self, forCellReuseIdentifier: cellIdentifier)
}
func numberOfRows() -> Int {
return rows.count
}
func configureCell(cell: UITableViewCell, indexPath: NSIndexPath) {
configure(cell as! Cell, rows[indexPath.row], indexPath)
}
}
class DataSource: NSObject, UITableViewDataSource {
var sections: [BaseSection] = []
func registerTableView(tableView: UITableView) {
for section in sections {
section.registerIdentifier(tableView)
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sections.count
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].numberOfRows()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = sections[indexPath.section].cellIdentifier
let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! UITableViewCell
sections[indexPath.section].configureCell(cell, indexPath: indexPath)
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment