我有一個包含6個元素的集合視圖,應該用3行和2列進行佈局。我用下面的代碼來實現這一目標:Swift:Collection查看未正確調整大小以便更改
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磅),然後o安輸出除非滾動到,只有2行而不是3和行之間的大間隙更改爲以下(參照圖像)細胞4 & 5關閉屏幕:
Collection view appearance when adjusted to account for hidden view
爲了situationally隱藏在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是真實的,如果它是隱藏bottomView,使的CollectionView 50分大,以填補空間。我在viewWillAppear中添加了這段代碼,希望collectionViewLayout能夠佔據額外的50點高度並進行相應的調整,但它不會。
嘗試在高度上創建較小的單元格。 –