3

I have a table view with a bunch of different sections and dynamic number of rows in each section. In the very first section I have a cell to 'select all'. Is there a quick and easy way to manually select all the cells, so the code in their didSelect triggers and next time the user presses one of the cells it triggers their didDeselect? The only way I can think of right now is to loop through all the sections, and in each section loop through 0 < indexPath.row < section's data array count and call

self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: UITableViewScrollPosition.none)
self.tableView(self.tableView, didSelectRowAt: indexPath)

but is there a way to do it without so much looping?

Tommy K
  • 1,759
  • 3
  • 28
  • 51
  • 1
    isn't it better you keep track of selected state of each cell in your data source? – HMHero May 02 '17 at 21:11
  • You should not be calling `didSelectRowAt` yourself. That's to let you know what the user did. It's pointless when you are explicitly calling `selectRow` because you already know the row has been selected. – rmaddy May 02 '17 at 21:23

2 Answers2

3

No; there is no way to do it without looping. You can make it a little easier on yourself by extending UITableView with a method to do it for you. This should do it:

extension UITableView {

    func selectAll(animated: Bool = false) {
        let totalSections = self.numberOfSections
        for section in 0 ..< totalSections {
            let totalRows = self.numberOfRows(inSection: section)
            for row in 0 ..< totalRows {
                let indexPath = IndexPath(row: row, section: section)
                // call the delegate's willSelect, select the row, then call didSelect
                self.delegate?.tableView?(self, willSelectRowAt: indexPath)
                self.selectRow(at: indexPath, animated: animated, scrollPosition: .none)
                self.delegate?.tableView?(self, didSelectRowAt: indexPath)
            }
        }
    }

}

Just add that to any of your Swift files at root level and then you can call tableView.selectAll() on any UITableView.

Robert
  • 6,660
  • 5
  • 39
  • 62
0

NSTableView has a selectAll method.

Scott Thompson
  • 22,629
  • 4
  • 32
  • 34