gpt4 book ai didi

swift - 更改 UITableViewCell 的 intrinsicContentSize 是如何工作的?

转载 作者:可可西里 更新时间:2023-11-01 01:34:47 26 4
gpt4 key购买 nike

我制作了一个 UITableView,其中的单元格在您点击它们时会展开。它模仿以下项目:https://github.com/rushisangani/TableViewCellExpand

基本上,单元格的容器 View 有两个 subview ,它们充当扩展/收缩状态的容器——“前”和“后”,每个都被限制在单元格的顶部、底部、前导和尾部边缘主要内容 View 。为了使单元格展开或收缩,我只需切换前 View 和后 View 底部约束上的 isActive 属性。这有效,但前提是我在点击时重新加载单元格。如果我只是更改约束,然后尝试调用 invalidateIntrinsicContentSize(),则什么也不会发生。

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
// Expand/contract the cell and invalidate size (doesn't work)
// let cell = tableView.cellForRow(at: indexPath) as! ExpandingCell
// cell.tap()
// cell.invalidateIntrinsicContentSize()

// Keep track of the selected index and configure the expand/contract state when the cell is remade
tableView.deselectRow(at: indexPath, animated: false)
expandedIndexPath = indexPath
if(!expandedIndexPathArray.contains(indexPath)){
expandedIndexPathArray.append(indexPath)
}
else{
expandedIndexPathArray = expandedIndexPathArray.filter({$0 != indexPath})
}

// Whenever a cell's intrinsicContentSize changes, it must be reloaded
tableView.reloadRows(at: [indexPath], with: .none)
}

幕后发生了什么?为什么单元格不能在不重新加载的情况下重新计算其大小?

最佳答案

如果你想根据内容的固有大小收缩/扩展单元格,你需要执行以下 3 个步骤:

  1. 配置 TableView :

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 44

    对于静态 TableView Controller ,您需要实现 heightForRowAtIndexPath 并返回 UITableViewAutomaticDimension

  2. 更新单元约束以反射(reflect)收缩/展开状态

  3. 要求 TableView 反射(reflect)变化:

    tableView.beginUpdates()
    tableView.endUpdates()

关于swift - 更改 UITableViewCell 的 intrinsicContentSize 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38607718/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com