【问题标题】:Swift: Collection View not adjusting correctly to change in sizeSwift:集合视图未正确调整以更改大小
【发布时间】: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

这会产生一个完美的集合视图,看起来像这样:

This is the desired output

但是,当我在加载视图之前将视图隐藏在集合视图下方并调整它的大小(使其高度高 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


【解决方案1】:

您需要使布局无效。它自己不会这样做。在调用 layoutIfNeeded() 之后,在流布局上调用 invalidateLayout()。

flowLayout.invalidateLayout()

【讨论】:

  • 非常感谢,我没想到会这样做。祝你有美好的一天!
  • 不客气。我轮流解决这个问题。我转来转去。我希望它是一劳永逸的。不是。
猜你喜欢
  • 2014-05-18
  • 1970-01-01
  • 2023-03-16
  • 2020-10-10
  • 2014-04-30
  • 1970-01-01
  • 1970-01-01
  • 2020-08-17
  • 1970-01-01
相关资源
最近更新 更多