swift - UICollectionViewFlowLayout estimatedItemSize 不适用于 iOS12,但它适用于 iOS 11。*

标签 swift uicollectionview uicollectionviewlayout ios12 uicollectionviewflowlayout

对于我们使用的 UICollectionView 的动态高度单元格,

if let layout = self.collectionViewLayout as? UICollectionViewFlowLayout {
    layout.estimatedItemSize = UICollectionViewFlowLayoutAutomaticSize
}

在高度和宽度的适当约束下,它适用于 iOS 11.* 版本,但它会中断并且不会使单元格在 iOS 12.0 上动态

最佳答案

在我的例子中,我通过向单元格的 contentView 显式添加以下约束来解决这个问题。

class Cell: UICollectionViewCell {
    // ...

    override func awakeFromNib() {
        super.awakeFromNib()

        // Addresses a separate issue and prevent auto layout warnings due to the temporary width constraint in the xib.
        contentView.translatesAutoresizingMaskIntoConstraints = false

        // Code below is needed to make the self-sizing cell work when building for iOS 12 from Xcode 10.0:
        let leftConstraint = contentView.leftAnchor.constraint(equalTo: leftAnchor)
        let rightConstraint = contentView.rightAnchor.constraint(equalTo: rightAnchor)
        let topConstraint = contentView.topAnchor.constraint(equalTo: topAnchor)
        let bottomConstraint = contentView.bottomAnchor.constraint(equalTo: bottomAnchor)
        NSLayoutConstraint.activate([leftConstraint, rightConstraint, topConstraint, bottomConstraint])
    }
}

这些约束已经存在于单元格的 xib 中,但不知何故它们对于 iOS 12 来说还不够。

建议在不同地方调用 collectionView.collectionViewLayout.invalidateLayout() 的其他线程对我的情况没有帮助。

示例代码在这里:https://github.com/larrylegend/CollectionViewAutoSizingTest

这会将解决方法应用于 https://medium.com/@wasinwiwongsak/uicollectionview-with-autosizing-cell-using-autolayout-in-ios-9-10-84ab5cdf35a2 教程中的代码:

关于swift - UICollectionViewFlowLayout estimatedItemSize 不适用于 iOS12,但它适用于 iOS 11。*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51718787/

相关文章:

iOS - 某些单元格不会调用 applyLayoutAttributes

ios - 在 iOS 设备上以编程方式测试蓝牙版本

ios - 在拒绝 UIActivityController 的“保存图像”权限后,如何将用户重定向到设置?

ios - 如何包装自调整大小的 UICollectionViewCell

ios - 单元格大小更改后,如何自动调整 CollectionViewCell 中内容的大小?

ios - UICollectionViewFlowLayout 中的自定义布局

ios - UITest 无法终止 com.test.abc :3708 after 60. 0s;状态仍然是`Running Foreground

ios - 在 URLSession.uploadTask :with :fromFile 上设置边界

ios - UIImageView 将(segue)nil 传递给另一个 ViewController

swift - 拖动和重新排序 - 带部分的 UICollectionview