[英]Swift: Collection View not adjusting correctly to change in size
我有一个包含 6 个元素的集合视图,这些元素应该用 3 行和 2 列进行布局。 我使用以下代码来实现这一点:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let totalWidth = collectionView.bounds.size.width - 12
let totalHeight = collectionView.bounds.size.height - 18
let heightOfView = (totalHeight / 3)
let dimensions = CGFloat(Int(totalWidth))
return CGSize(width: dimensions / 2, height: heightOfView)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 6
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(0, 5, 0, 5)
}
在 viewDidLoad 中:
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
collectionView.delegate = self
flowLayout.scrollDirection = .horizontal
flowLayout.minimumLineSpacing = 5
flowLayout.minimumInteritemSpacing = 5
这会产生一个看起来像这样的集合视图,这是完美的:
但是,当我在加载视图之前根据情况隐藏集合视图下方的视图并调整其大小(使其高度高 50 pts)时,输出更改为以下(参见图像),单元格 4 和 5 关闭除非滚动到屏幕,否则只有 2 行而不是 3 行,并且行之间有很大的差距:
为了在 viewWillAppear 中隐藏视图,我添加了以下内容:
override func viewWillAppear(_ animated: Bool) {
if testVariable == true {
bottomView.isHidden = true
// make bottomView height = 0
bottomViewHeight.constant = 0
// make collectionView space to the bottom of the view controller 0
collectionToBase.constant = 0
view.layoutIfNeeded()
}
}
此代码测试 testVariable 是否为真,如果为真,则隐藏底部视图并使 collectionView 大 50 pts 以填充空间。 我在 viewWillAppear 中添加了这段代码,希望 collectionViewLayout 可以考虑额外的 50 pts 高度并根据需要进行调整,但事实并非如此。
您需要使布局无效。 它不会自己这样做。 在调用 layoutIfNeeded() 之后,在流布局上调用 invalidateLayout()。
flowLayout.invalidateLayout()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.