Skip to content

Instantly share code, notes, and snippets.

@jmnavarro
Created October 27, 2015 15:43
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 jmnavarro/b3feb69a2e3f3d899ba1 to your computer and use it in GitHub Desktop.
Save jmnavarro/b3feb69a2e3f3d899ba1 to your computer and use it in GitHub Desktop.
Protocol based UITableView
struct Employee {
let name: String
let salary: Int
}
// This is the link between the model and the view
// Mascot <-> MascotTableViewCell
extension CollectionType where Generator.Element == Employee {
func elementByPosition(position: Int) -> Self.Generator.Element? {
// dirty hack. It's already implemented in Array subscript with O(1) instead of O(n)
var i = 0
for e in self {
if i++ == position {
return e
}
}
return nil
}
func cellInTable(tableView: UITableView, forRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("employee", forIndexPath: indexPath) as! EmployeeTableViewCell
cell.employee = self.elementByPosition(indexPath.row)
return cell
}
}
class EmployeeTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel?
@IBOutlet weak var salaryLabel: UILabel?
var employee: Employee? {
didSet {
nameLabel?.text = employee?.name
salaryLabel?.image = employee?.salary
}
}
}
var employees = [Employee]()
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return self.employees.cellInTable(tableView, forRowAtIndexPath: indexPath)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment