Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import UIKit
final class MovieTableViewCell: UITableViewCell {
struct ViewModel {
let title: String
}
func bind(_ viewModel: ViewModel) {
textLabel?.text = viewModel.title
}
}
extension MovieTableViewCell.ViewModel {
init(_ movie: Movie) {
self.title = movie.title
}
}
final class HomeViewController: UIViewController {
private var movies = [Movie]()
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.backgroundColor = .white
tableView.delegate = self
tableView.dataSource = self
tableView.register(MovieTableViewCell.self, forCellReuseIdentifier: "\(MovieTableViewCell.self)")
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
edgesForExtendedLayout = []
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
])
}
}
extension HomeViewController: UITableViewDelegate {
}
extension HomeViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movies.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "\(MovieTableViewCell.self)", for: indexPath) as? MovieTableViewCell else {
fatalError("Inconsitent data source")
}
let movie = movies[indexPath.row]
let viewModel = MovieTableViewCell.ViewModel(movie)
cell.bind(viewModel)
return cell
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.