如何在特定部分重新加载选定的单元格以在 tableview Swift 中展开/折叠

问题描述

我正在我的 iOS 应用程序中执行展开/折叠 tableview 单元格功能我有多个部分。每个部分都有多个单元格。认情况下,单元格高度为 100,一旦用户点击单元格,我将高度增加到 200。

因此,基于 Bool 值,我正在更改它。但是,在滚动 tableview 时,它会在部分之间交换展开/折叠的单元格。 就像我点击第一部分的第一个单元格一样,它正在扩展,但是在滚动 tableview 后,第二部分的第一个单元格也在扩展。

我的要求是,如果用户点击特定单元格,则该单元格仅应展开/折叠。用户可以手动展开和关闭用户可以展开多个单元格。

所以,我尝试存储 Indexpath 行和部分。

         var expandedindexSet : IndexSet = []
             var expandedindexSection : IndexSet = []
         
             func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
                 let cell = tableView.dequeueReusableCell(withIdentifier:"cellIdentifier",for:
         indexPath) as! MyTableViewCell
         
if expandedindexSet.contains(indexPath.row) && expandedindexSection.contains(indexPath.section) { // expanded true
                     cell.height = 200
                    //some other data loading here
                 }
                 else {  //expanded false
              cell.height = 100
                 }
              }
         
             @IBAction moreButtonTapped(_ sender: Any) {
                 
                 if(expandedindexSet.contains(indexPath.row)) && expandedindexSection.contains(indexPath.section){
                     expandedindexSet.remove(indexPath.row)
                     expandedindexSection.remove(indexPath.section)
                     
                 } else {
                     expandedindexSet.insert(indexPath.row)
                     expandedindexSection.insert(indexPath.section)
                 }
                 entriesTableView.beginUpdates()
                 entriesTableView.reloadRows(at: [indexPath],with: .none)
                 entriesTableView.endUpdates()
             }

谁能给出比这更好的方法

解决方法

如果您在单独的数组中独立存储部分和行,您的算法将失败。 原因是两者都是依赖的: 考虑三个展开的单元格 (row:1,section:1),(row:2,(row:3,section:2)

现在单元格 (row:3,section:1) 会发生什么? row-array 包含值“3”,section-array 包含值“1”,因此将被视为扩展。

因此,需要将索引路径存储为一个整体——见示例代码:

var expanded:[IndexPath] = []

expanded.append(IndexPath(row:1,section:1))
expanded.append(IndexPath(row:2,section:1))
expanded.append(IndexPath(row:3,section:2))

let checkPath = IndexPath(row:3,section:1)
if (expanded.contains(checkPath)) {
    print ("is expanded")
} else {
    print ("collapsed")
}

更新

因此,在您的按钮句柄中,您将执行以下操作:

@IBAction moreButtonTapped(_ sender: Any) {
    
    if(expanded.contains(indexPath)) {
        expanded.removeAll { (checkPath) -> Bool in
            return checkPath == indexPath
        }
    } else {
        expanded.append(indexPath)
    }
    entriesTableView.beginUpdates()
    entriesTableView.reloadRows(at: [indexPath],with: .none)
    entriesTableView.endUpdates()
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...