我正在为调整集合视图的大小而烦恼。
目前我有一个计算大小的流式布局方法。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if let cell = collectionView.cellForItem(at: indexPath) {
let pokemonCell = cell as! PokemonCell
pokemonCell.setNeedsDisplay()
}
return CGSize(width: 150, height: collectionView.bounds.size.height)
}
还有两种方法用于调整旋转时的大小。
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
guard let flowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout else {
return
}
flowLayout.invalidateLayout()
self.collectionView.reloadData()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
collectionView.frame = self.view.bounds
self.collectionView.reloadData()
}
单元格内容在容器中居中 当我改变布局时,单元格内容开始跳动。它们有的重新定位,有的保持在 y 前一个布局的位置。有时内容得到了正确的位置,但在滚动时又回到了原来的位置。
尝试 https:/developer.apple.comdocumentationuikituicollectionviewlayout1617728-invalidatelayout。
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
collectionView.collectionViewLayout.invalidateLayout()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.frame = self.view.bounds
}
invalidateLayout 使集合视图的布局无效。但是这个方法不会强制立即更新。它的工作原理类似于UIView setNeedsLayout。
不要在layout的方法中调用reloadData。
也可以查看答案。UICollectionView在边界改变时无效布局。 和 Swift: 如何在设备旋转后刷新UICollectionView的布局