Last active
February 21, 2021 17:17
-
-
Save meyusufdemirci/25a4f1c4fa1b8e8b21e55ff9a2198a99 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import UIKit | |
| class ListController: UITableViewController { | |
| // MARK: Properties | |
| private let searchController: UISearchController = { | |
| let controller: UISearchController = UISearchController() | |
| controller.searchBar.placeholder = "Search" | |
| controller.obscuresBackgroundDuringPresentation = false | |
| return controller | |
| }() | |
| private let viewModel: ListViewModel | |
| init(viewModel: ListViewModel = ListViewModel()) { | |
| self.viewModel = viewModel | |
| super.init(style: .grouped) | |
| self.viewModel.delegate = self | |
| } | |
| required init?(coder: NSCoder) { | |
| fatalError("init(coder:) has not been implemented") | |
| } | |
| override func viewDidLoad() { | |
| super.viewDidLoad() | |
| navigationItem.searchController = searchController | |
| searchController.searchResultsUpdater = self | |
| } | |
| override func viewDidAppear(_ animated: Bool) { | |
| super.viewDidAppear(animated) | |
| viewModel.refreshCoins() | |
| } | |
| } | |
| // MARK: - TableView | |
| extension ListController { | |
| override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
| return viewModel.coins.count | |
| } | |
| override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
| let coin = viewModel.coins[indexPath.row] | |
| let cell = UITableViewCell(style: .value1, reuseIdentifier: "\(indexPath.section)_\(indexPath.row)") | |
| cell.textLabel?.text = coin.symbol | |
| cell.detailTextLabel?.text = "\(coin.price)" | |
| return cell | |
| } | |
| override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { | |
| tableView.deselectRow(at: indexPath, animated: true) | |
| let coin = viewModel.coins[indexPath.row] | |
| let coinViewModel = CoinViewModel(coin: coin) | |
| let coinController = CoinController(viewModel: coinViewModel) | |
| navigationController?.show(coinController, sender: self) | |
| } | |
| } | |
| // MARK: - UISearchResultsUpdating | |
| extension ListController: UISearchResultsUpdating { | |
| func updateSearchResults(for searchController: UISearchController) { | |
| viewModel.search(searchController.searchBar.text) | |
| } | |
| } | |
| // MARK: - ListDelegate | |
| extension ListController: ListDelegate { | |
| func coinsDidRefresh() { | |
| tableView.reloadData() | |
| } | |
| func coinsCouldNotRefresh() { | |
| // An error occured | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment