Last active
July 24, 2020 10:34
-
-
Save Enriquecm/f35df4bd056d693d17d83d9f89f86eb0 to your computer and use it in GitHub Desktop.
UITableView selection programmatically
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
// MARK: UITableViewCell class | |
class TableViewCell: UITableViewCell { | |
override var isSelected: Bool { | |
didSet { | |
// Configure cell selection | |
} | |
} | |
} | |
// MARK; UIViewController class | |
class ViewController: UIViewController { | |
private let viewModel = ViewModel() | |
// ... | |
} | |
extension ViewController: UITableViewDelegate { | |
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { | |
viewModel.didSelect(indexPath: indexPath) | |
} | |
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { | |
viewModel.didDeselect(indexPath: indexPath) | |
} | |
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { | |
cell.isSelected = viewModel.isSelected(indexPath: indexPath) | |
} | |
} | |
// MARK: ViewModel class | |
class ViewModel { | |
private var selectedHash = [IndexPath: Bool]() | |
func isSelected(indexPath: IndexPath) -> Bool { | |
return selectedHash[indexPath] ?? false | |
} | |
func didSelect(indexPath: IndexPath) { | |
selectedHash[indexPath] = true | |
} | |
func didDeselect(indexPath: IndexPath) { | |
selectedHash[indexPath] = false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment