ios - 当前单元格展开时折叠其他 UITableViewCell

标签 ios swift uitableview

我正在尝试扩展我的 UITableViewCell 并且我可以扩展单元格。但我想折叠未选中的 UITableViewCell

我在代码中尝试的内容:

var expandedCells = [Int]()
@IBOutlet weak var tableVieww:UITableView!
@IBAction func buttonPressed(_ sender: AnyObject) {
    // If the array contains the button that was pressed, then remove that button from the array
    if expandedCells.contains(sender.tag) {
        expandedCells = expandedCells.filter({ $0 != sender.tag})
    }
        // Otherwise, add the button to the array
    else {
        expandedCells.append(sender.tag)
    }
    // Reload the tableView data anytime a button is pressed
    tableVieww.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 20

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! exampleCell
    cell.myButton.tag = indexPath.row
    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    // Set the row height based on whether or not the Int associated with that row is contained in the expandedCells array
    if expandedCells.contains(indexPath.row) {
        return 212
    } else {
        return 57
    }
}

最佳答案

您可以维护一个变量来维护所选索引,如下所示,

var expandedIndexPath: IndexPath?

然后按如下方式更新您的 tableView 委托(delegate),

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    expandedIndexPath = indexPath // Update the expandedIndexPath with the selected index
    tableView.reloadData() // Reload tableview to reflect the change
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    // Check wether expanded indexpath is the current index path and updated return the respective height
    if expandedIndexPath == indexPath {
        return 212
    } else {
        return 57
    }
}

这应该可以正常工作。

关于ios - 当前单元格展开时折叠其他 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46537726/

相关文章:

ios - 在 UITableView 下(末尾)添加空(空白)空间

ios - 单击按钮后跳转到该详细信息时,如何为 UITableViewCell 创建详细信息?

iphone - 旋转自定义 UITableViewCell

ios - iOS 推送通知的远程声音

ios - CLLocationManager 不在 iOS 10.2 [Swift] 中调用 didUpdateLocation()

ios - 保存到图库后检索视频资源

swift - 我们如何在 UITableView 中从本地 Realm 检索数据?

xcode - Swift:类型 (_)-> 的值没有成员 'Generator'

objective-c - iOS CoreText : CTFrameSetter is making wider lines than the CGPath allows

iphone - GuitarToolkit 如何在后台显示持久的事件横幅?