Landscape orientation for Collection View in Swift

前端 未结 4 2237
终归单人心
终归单人心 2021-01-23 03:38

I am encountering a problem on landscape orientation for my collection view cell. When the app is in portrait it gives me the correct number of cell per row which is 2. But when

4条回答
  •  遇见更好的自我
    2021-01-23 03:50

    Just reload your UICollectionView in

    override

    func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
            super.viewWillTransition(to: size, with: coordinator)
    
            yourCollectionView.reloadData()
        }
    

    and your collection view layout will refresh again when orientation changed

    Update: This is code snippet for collectionView layout making 4 image view in each row from my code, and its working even it changing orientation from portrait to landscape and vice versa. You can change it to your need:

    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: UIScreen.main.bounds.width / 4.8, height: UIScreen.main.bounds.width / 4.8)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    
        return UIEdgeInsets(top: 0.0, left: 0.0, bottom: 0.0, right: 0.0)
    }
    
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    
        return 0.0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout
        collectionViewLayout: UICollectionViewLayout,
                        minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    
        return 16.0
    }
    

    Hope it will helps you.

    Cheers!

提交回复
热议问题