Skip to content

Instantly share code, notes, and snippets.

@Enriquecm
Last active July 24, 2020 10:34
Show Gist options
  • Save Enriquecm/f35df4bd056d693d17d83d9f89f86eb0 to your computer and use it in GitHub Desktop.
Save Enriquecm/f35df4bd056d693d17d83d9f89f86eb0 to your computer and use it in GitHub Desktop.
UITableView selection programmatically
// 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