ios - 防止 sizeForItemAt 由于重用动态 collectionView 单元格而使用错误的单元格大小

标签 ios swift autolayout uicollectionviewcell

我使用自动布局来动态计算 collectionView 单元格的大小。一些单元格在第一次滚动到查看端口时使用来自重用单元格的尺寸。当我继续滚动 collectionView 时,它们将被设置为正确的值。

在我的 sizeForItemAt 中,我有以下内容:

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if let cachedSize = cachedHeightForIndexPath[indexPath] {
            return cachedSize
        }

        if let cell = collectionView.cellForItem(at: indexPath) {
            cell.setNeedsLayout()
            cell.layoutIfNeeded()
            let size = cell.contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
            cachedHeightForIndexPath[indexPath] = size
            print("value is \(size) for indexpath: \(indexPath)")
            return size
        }
        return CGSize(width: ScreenSize.width, height: 0.0)
    }

我有三个 session ,第一部分所有单元格的高度理论上都等于 88,所有其他部分所有单元格的高度都等于 104。

最初,只有第一部分是可见的。从控制台中,我可以看到单元格的高度按预期设置为 88.0。当我滚动到其余部分(第一部分将不可见,单元格将被重复使用)时,第二部分和第三部分的一些单元格在第一次滚动到查看端口时使用值 88.0 作为单元格的高度,而不是 104 . 当我继续滚动时,错误大小的单元格将使用 104 作为维度。我们如何强制所有单元格重新计算高度并且不使用旧单元格的高度。

最佳答案

您的想法是正确的,但是当您通过调用 systemLayoutSizeFitting 而不是在 existing 单元格 (collectionView.cellForItem),你需要用一个 model 单元格武装自己,你配置的单元格与 cellForItem 会配置它并测量那个

我是这样做的(与您所拥有的非常相似,只有一点不同;另外,我将尺寸存储在模型中):

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let memosize = self.sections[indexPath.section].itemData[indexPath.row].size
    if memosize != .zero {
        return memosize
    }
    self.configure(self.modelCell, forIndexPath:indexPath) // in common with cellForItem
    var sz = self.modelCell.contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
    sz.width = ceil(sz.width); sz.height = ceil(sz.height)
    self.sections[indexPath.section].itemData[indexPath.row].size = sz // memoize
    return sz
}

关于ios - 防止 sizeForItemAt 由于重用动态 collectionView 单元格而使用错误的单元格大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56369764/

相关文章:

iOS 自动布局 - 如何在旋转时拥有一个粘性 subview (如 native 相机应用程序)?

ios - 如何忽略多点触控序列中的某些 UITouch 点

ios - 在 swift 2 中恢复消耗品(硬币)

ios - heightForImageCellAtIndexPath 中 dispatch_once 的原因

swift - 嵌套函数 - 缺少参数参数

ios - 自动布局和动画

ios - 通过调用 openURL 方法强制 safari 在同一选项卡中打开 url

ios - UITableView 自定义单元格点击文本字段时自动滚动 : Swift 3

swift - 取消 URLSessionStreamTask 永远不会使用 NSURLErrorCancelled 调用completionHandler(在 macOS 上)

ios - 如何使用自动布局相对于 UIView 高度移动 UILabel?