Sample project to reproduce the issue: https://github.com/Coeur/StackOverflow51375566推荐答案对于所有解决方案,请注意,无需在viewDidLoad中显式调用reloadData:它将自动发生.For all solutions, note that there is no need to explicitly call reloadData in viewDidLoad: it will happen automatically.受 Samantha想法的启发:invalidateLayout在viewDidLoad中异步.override func viewDidLoad() { super.viewDidLoad() //[...] for _ in 0 ..< 1000 { array.append(randomKeyByBitLength(Int(arc4random_uniform(8)))!) } DispatchQueue.main.async { self.collectionView.collectionViewLayout.invalidateLayout() }}解决方案2 (不完美,请参见DHennessy13的改进)基于 Peter Lapisu的答案. viewWillLayoutSubviews中的invalidateLayout.override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() collectionView.collectionViewLayout.invalidateLayout()}如DHennessy13所指出的那样,当前使用viewWillLayoutSubviews的解决方案是不完善的,因为它将在旋转屏幕时使Layout无效.As noted by DHennessy13, this current solution with viewWillLayoutSubviews is imperfect as it will invalidateLayout when rotating the screen.关于此解决方案,您可以遵循 DHennessy13的改进.You may follow DHennessy13 improvement regarding this solution.基于 Tyler Sheaffer答案,肖恩·奥克斯塔克(Shawn Aukstak)港口通向斯威夫特(Swift)和萨曼莎(Samantha)的想法.子类化您的CollectionView以便在layoutSubviews上执行invalidateLayout.class AutoLayoutCollectionView: UICollectionView { private var shouldInvalidateLayout = false override func layoutSubviews() { super.layoutSubviews() if shouldInvalidateLayout { collectionViewLayout.invalidateLayout() shouldInvalidateLayout = false } } override func reloadData() { shouldInvalidateLayout = true super.reloadData() }}此解决方案很优雅,因为它不需要更改ViewController代码.我已经在此示例项目 https://github.com/Coeur/StackOverflow51375566的分支AutoLayoutCollectionView上实现了它/tree/AutoLayoutCollectionView .This solution is elegant as it doesn't require to change your ViewController code. I've implemented it on branch AutoLayoutCollectionView of this sample project https://github.com/Coeur/StackOverflow51375566/tree/AutoLayoutCollectionView.重写UICollectionViewCell默认约束.参见拉里答案.Rewrite UICollectionViewCell default constraints. See Larry answer.执行collectionView(_:layout:sizeForItemAt:)并返回cell.contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).参见哑光答案. 这篇关于在iOS 12中,何时UICollectionView布局单元格在笔尖中使用自动布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-10 21:33