Created
July 10, 2016 00:14
-
-
Save nathanborror/7f2163b3eba40ca52909c1ac7f668bcb to your computer and use it in GitHub Desktop.
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
// 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