Skip to content

Instantly share code, notes, and snippets.

@nathanborror
Created July 10, 2016 00:14
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 nathanborror/7f2163b3eba40ca52909c1ac7f668bcb to your computer and use it in GitHub Desktop.
Save nathanborror/7f2163b3eba40ca52909c1ac7f668bcb to your computer and use it in GitHub Desktop.
// Table Cells
protocol TableCell {
associatedtype A: Any
associatedtype Cell: UITableViewCell
static func cell(for items: [A], at indexPath: IndexPath, of tableView: UITableView, configure: (cell: Cell, item: A) -> Void) -> Cell
}
extension TableCell {
static func cell(for items: [A], at indexPath: IndexPath, of tableView: UITableView, configure: (cell: Cell, item: A) -> Void) -> Cell {
let item = items[indexPath.row]
let cell = tableView.dequeueReusableCell(Cell.self)
configure(cell: cell, item: item)
return cell
}
}
// Table Actions
protocol TableAction {
associatedtype A: Accountable
static func actions(for items: [A], onDelete: ((A) -> Void)?, onEdit: ((A) -> Void)?) -> [UITableViewRowAction]
static func can(edit items: [A], at indexPath: IndexPath) -> Bool
}
extension TableAction {
static func actions(for items: [A], onDelete: ((A) -> Void)?, onEdit: ((A) -> Void)?) -> [UITableViewRowAction] {
let delete = UITableViewRowAction(style: .destructive, title: "Delete") { _, indexPath in
let item = items[indexPath.row]
onDelete?(item)
}
let edit = UITableViewRowAction(style: .normal, title: "Edit") { _, indexPath in
let item = items[indexPath.row]
onEdit?(item)
}
return [delete, edit]
}
static func can(edit items: [A], at indexPath: IndexPath) -> Bool {
guard let account = Readernaut.app.me else { return false }
let item = items[indexPath.row]
return item.account.id == account.id
}
}
// Note
extension Note: TableCell, TableAction {
typealias A = Note
typealias Cell = NoteCell
static func cell(for notes: [A], at indexPath: IndexPath, of tableView: UITableView) -> Cell {
return Note.cell(for: notes, at: indexPath, of: tableView) { cell, note in
cell.set(note.book.title, body: note.text, timestamp: note.created.description)
cell.pictureURL = note.account.photo
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment