Select ALL TableView Rows Programmatically Using selectRowAtIndexPath

不羁岁月 提交于 2019-12-05 06:49:19

At the time allJobsSelected becomes true, you need to call the UITableView method selectRowAtIndexPath(_:animated:scrollPosition:) for each row of your table. In my case, I attached this functionality to the right bar button item which I named Select All. Calling this from cellForRowAtIndexPath is surely not the right place.

@IBAction func doSelectAll(sender: UIBarButtonItem) {
    let totalRows = tableView.numberOfRowsInSection(0)
    for row in 0..<totalRows {
        tableView.selectRowAtIndexPath(NSIndexPath(forRow: row, inSection: 0), animated: false, scrollPosition: UITableViewScrollPosition.None)
    }
}

For Swift 3 and answering your question literally, regardless of your code.

func selectAllRows() {
    for section in 0..<tableView.numberOfSections {
        for row in 0..<tableView.numberOfRows(inSection: section) {
            tableView.selectRow(at: IndexPath(row: row, section: section), animated: false, scrollPosition: .none)
        }
    }
}

If you want to inform the tableview delegate, use this method:

func selectAllRows() {
    for section in 0..<tableView.numberOfSections {
        for row in 0..<tableView.numberOfRows(inSection: section) {
            let indexPath = IndexPath(row: row, section: section)
            _ = tableView.delegate?.tableView?(tableView, willSelectRowAt: indexPath)
            tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
            tableView.delegate?.tableView?(tableView, didSelectRowAt: indexPath)
        }
    }
}

Functional solution (Swift 5.1)

extension UITableViewDataSource where Self: UITableView {
  /**
   * Returns all IndexPath's in a table
   * ## Examples:
   * table.indexPaths.forEach {
   *    selectRow(at: $0, animated: true, scrollPosition: .none) // selects all cells
   * }
   */
  public var indexPaths: [IndexPath] {
     return (0..<self.numberOfSections).indices.map { (sectionIndex: Int) -> [IndexPath] in
        (0..<self.numberOfRows(inSection: sectionIndex)).indices.compactMap { (rowIndex: Int) -> IndexPath? in
           IndexPath(row: rowIndex, section: sectionIndex)
        }
        }.flatMap { $0 }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!