繁体   English   中英

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

[英]How to reload selected cell in particular section for expand/collapse in tableview Swift

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

所以,基于布尔值,我正在改变它。 但是,在滚动表格视图时,它正在交换部分之间的展开/折叠单元格。 就像我点击第一部分的第一个单元格一样,它正在扩展,但是在滚动表格视图之后,第二部分的第一个单元格也在扩展。

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

因此,我尝试存储 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()
             }

任何人都可以提供比这更好的方法吗?

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

现在单元格(行:3,部分: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()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM