【发布时间】:2017-02-14 14:34:09
【问题描述】:
我有一个包含 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 行之间的差距很大:
Collection view appearance when adjusted to account for hidden view
为了根据情况隐藏 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 pts 以填充空间。我在 viewWillAppear 中添加了这段代码,希望collectionViewLayout 会考虑额外的 50 pts 高度并进行相应调整,但它没有。
【问题讨论】:
-
尝试在高度上创建较小的单元格。
标签: ios swift uicollectionview