Created
January 4, 2017 01:02
-
-
Save fmo91/84a5997b9ac531225c16dfddef15289c to your computer and use it in GitHub Desktop.
A sample UITableView delegate and data source implemented as a separated object
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
// | |
// DogsTableViewDriver.swift | |
// MediumSamples | |
// | |
// Created by Fernando Ortiz on 1/3/17. | |
// Copyright © 2017 Fernando Martín Ortiz. All rights reserved. | |
// | |
import UIKit | |
final class DogsTableViewDriver: NSObject { | |
// 1 | |
var dogs = [Dog]() | |
// 2 | |
let tableView: UITableView | |
// 3 | |
weak var delegate: DogsTableViewDriverDelegate? | |
init(tableView: UITableView) { | |
self.tableView = tableView | |
super.init() | |
configure() | |
} | |
private func configure() { | |
DogTableViewCell.register(in: tableView) | |
// 4 | |
tableView.delegate = self | |
tableView.dataSource = self | |
} | |
// 5 | |
func reload(with dogs: [Dog]) { | |
self.dogs = dogs | |
tableView.reloadData() | |
} | |
} | |
extension DogsTableViewDriver: UITableViewDelegate, UITableViewDataSource { | |
func numberOfSections(in tableView: UITableView) -> Int { | |
return 1 | |
} | |
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return dogs.count | |
} | |
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cell = DogTableViewCell.dequeue(from: tableView) | |
cell.configure(with: dogs[indexPath.row]) | |
return cell | |
} | |
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { | |
delegate?.didSelectedDog(dogs[indexPath.row]) | |
} | |
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { | |
return DogTableViewCell.height | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment