Suppose your UITableView
's data source is
struct Item {
id: Int
}
var dataSource: [Item] = []
You should select all ids from above data source, like so:
let result = dataSource.map{ $0.id }
If you need to change the user interface to select UITableViewCell
s, you have to create a new property isSelected
in your struct, because you cannot change selection state of a UITableViewCell
that is not visible, so begin by adding the new property:
struct Item {
id: Int
var isSelected = false
}
Now you will use above data source to change the selection state, like so
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
private var dataSource = [Item]()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Toggle", style: .plain, target: self, action: #selector(selectAllAction))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Acknowledge", style: .plain, target: self, action: #selector(acknowledgeAction))
self.tableView.allowsMultipleSelection = true
self.tableView.dataSource = self
self.tableView.delegate = self
}
@objc func selectAllAction() {
let totalRows = self.dataSource.count
let isSelectAll = self.dataSource.first(where: { !$0.isSelected }) != nil
for index in 0..<totalRows {
self.dataSource[index].isSelected = isSelectAll
}
self.tableView.visibleCells.forEach {
$0.setSelected(isSelectAll, animated: true)
}
}
@objc func acknowledgeAction() {
let result = self.dataSource.compactMap{ $0.isSelected ? $0.id : nil }
print(result)
guard !result.isEmpty else { return }
// send selected id(s) to the server
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.isSelected = self.dataSource[indexPath.row].isSelected
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.dataSource[indexPath.row].isSelected = true
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
self.dataSource[indexPath.row].isSelected = false
}
}