以编程方式选择 tableview 中的所有单元格,以便下次按下它们时调用 didDeselect [英] programmatically select all cells in tableview so next time they are pressed they call didDeselect

查看:31
本文介绍了以编程方式选择 tableview 中的所有单元格,以便下次按下它们时调用 didDeselect的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格视图,其中包含许多不同的部分和每个部分中的动态行数.在第一部分,我有一个全选"单元格.是否有一种快速简便的方法来手动选择所有单元格,以便其 didSelect 中的代码触发,下次用户按下其中一个单元格时,它会触发其 didDeselect?我现在能想到的唯一方法是遍历所有部分,并在每个部分中通过 0 <indexPath.row <部分的数据数组计数并调用

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?

推荐答案

;没有循环就没有办法做到这一点.你可以通过扩展 UITableView 一个方法来让你自己更容易一些.应该这样做:

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)
            }
        }
    }

}

只需将其添加到根级别的任何 Swift 文件中,然后您就可以在任何 UITableView 上调用 tableView.selectAll().

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

这篇关于以编程方式选择 tableview 中的所有单元格,以便下次按下它们时调用 didDeselect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆