Created
October 27, 2015 15:43
-
-
Save jmnavarro/b3feb69a2e3f3d899ba1 to your computer and use it in GitHub Desktop.
Protocol based UITableView
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
struct Employee { | |
let name: String | |
let salary: Int | |
} |
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
// 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 | |
} | |
} |
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
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 | |
} | |
} | |
} |
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
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