[英]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.