简体   繁体   English

横向模式下的Swift Collection View

[英]Swift Collection View in landscape mode

So i'm building an app where i have a collection view with 2 cells in a row. 所以我正在构建一个应用程序,其中我有一个连续有2个单元格的集合视图。 But when i rotate my screen i want to change that for example to 4. How do i do that? 但是,当我旋转屏幕时,例如要将其更改为4。我该怎么做?

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let cellWidth =  (view.frame.size.width - 50) / 2
    return CGSize(width: cellWidth, height: cellWidth)
}

override func viewWillTransition(to size: CGSize,
                                 with coordinator: UIViewControllerTransitionCoordinator)
{
    collectionView?.collectionViewLayout.invalidateLayout()
}

Add super method in viewWillTransition . viewWillTransition添加超级方法。

super.viewWillTransition(to: size, with: coordinator)

This will allow the superview to pass this method class to all of its subviews. 这将允许超级视图将此方法类传递给其所有子视图。

override func viewWillTransition(to size: CGSize,
                             with coordinator: UIViewControllerTransitionCoordinator)
{
      super.viewWillTransition(to: size, with: coordinator)
      collectionView?.collectionViewLayout.invalidateLayout()
}

This code helped me in my problem. 这段代码帮助我解决了问题。

func collectionView(_ collectionView: UICollectionView,
                    layout collectionViewLayout: UICollectionViewLayout,
                    sizeForItemAt indexPath: IndexPath) -> CGSize {
    let cellWidth =  (view.frame.size.width - 50) / 2
    if UIDevice.current.orientation.isLandscape {
        return CGSize(width: (cellWidth-30)/2, height: (cellWidth-30)/2)
    } else {
        return CGSize(width: cellWidth, height: cellWidth)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM