【问题标题】:UICollectionView resize on screen rotationUICollectionView 在屏幕旋转时调整大小
【发布时间】:2020-05-01 22:46:24
【问题描述】:

我正在努力调整集合视图的大小。

目前我有一个计算大小的流布局方法:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if let cell = collectionView.cellForItem(at: indexPath) {
            let pokemonCell = cell as! PokemonCell
            pokemonCell.setNeedsDisplay()
        }
        return CGSize(width: 150, height: collectionView.bounds.size.height)
    }

还有两种调整旋转大小的方法:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransition(to: size, with: coordinator)
    guard let flowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout else {
        return
    }
    flowLayout.invalidateLayout()
    self.collectionView.reloadData()
}

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()

    collectionView.frame = self.view.bounds
    self.collectionView.reloadData()

}

单元格内容在容器中居中。当我更改布局时,单元格内容开始跳跃。其中一些重新定位自己,一些保留在先前布局的 y 位置。有时内容会得到正确的位置,然后会在滚动时返回。

screenshot

【问题讨论】:

    标签: swift uicollectionview uikit uicollectionviewflowlayout


    【解决方案1】:

    试试https://developer.apple.com/documentation/uikit/uicollectionviewlayout/1617728-invalidatelayout

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        collectionView.collectionViewLayout.invalidateLayout()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        collectionView.frame = self.view.bounds
    }
    

    invalidateLayout 使集合视图的布局无效。但此方法不会强制立即更新。它的工作原理类似于 UIView setNeedsLayout。

    不要在布局的方法中调用 reloadData。

    同时检查答案:UICollectionView Invalidate Layout On Bounds ChangesSwift: How to refresh UICollectionView layout after rotation of the device

    【讨论】:

      猜你喜欢
      • 2022-07-15
      • 2014-06-20
      • 1970-01-01
      • 2018-04-30
      • 2016-04-20
      • 1970-01-01
      • 2016-03-12
      • 2013-05-01
      • 1970-01-01
      相关资源
      最近更新 更多