想要提供替代解决方案。我不喜欢在协调器的动画完成中调用 reloadData 或 performBatchUpdates 的轻微延迟。两者都导致了 AutoLayout 警告。
在 viewWillTransitionToSize 内,在所有可见的嵌套集合视图上调用 invalidateLayout,最后在外层/顶层集合视图上调用 invalidateLayout。
我的集合视图单元格有一个子集合视图:
class NestableCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var collectionView: NestableCollectionView?
}
扩展 UICollectionView 以使嵌套的集合视图无效:
class NestableCollectionView: UICollectionView {
func invalidateNestedCollectionViews(){
let visibleCellIndexPaths = self.indexPathsForVisibleItems()
for cellIndex in visibleCellIndexPaths {
if let nestedCell = self.cellForItemAtIndexPath(cellIndex) as? NestableCollectionViewCell {
// invalidate any child collection views
nestedCell.collectionView?.invalidateNestedCollectionViews()
// finally, invalidate the cell's own collection view
nestedCell.collectionView?.collectionViewLayout.invalidateLayout()
}
}
}
}
并且,在 willTransitionToSize 上无效:
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
self.collectionView.invalidateNestedCollectionViews()
self.collectionView.collectionViewLayout.invalidateLayout()
}