How to check if device orientation is landscape left or right in swift?

前端 未结 7 1206
伪装坚强ぢ
伪装坚强ぢ 2021-02-03 21:22
    if UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation) {
        print(\"landscape\")
    }
    if UIDeviceOrientationIsPortrait(UIDevice.currentDev         


        
7条回答
  •  轮回少年
    2021-02-03 21:49

    There is one thing that destroy all this answers - it's iOS9 iPad multitasking.

    On iOS 9, an iPad app by default opts into iPad multitasking. This means that it must adopt all orientations at all times. Since you have not opted out of iPad multitasking, the runtime assumes that you do adopt all orientations at all times — and thus it doesn't need to bother to ask you what orientations you permit, as it already knows the answer (all of them).

    To do right cell size for UICollectionView I do next :

    func collectionView(_ collectionView: UICollectionView, layout 
        collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    
            if UIDevice.current.userInterfaceIdiom == .phone {
                return CGSize(width: collectionView.frame.size.width, height: 120)
            } else {
                var width:CGFloat = 0
                let height = 250
                // because of iOS9 and iPad multitasking
                if (UIApplication.shared.statusBarOrientation.rawValue <= UIInterfaceOrientation.portraitUpsideDown.rawValue) {
                    width = (collectionView.frame.size.width - 3) / 3
                } else {
                    width = (collectionView.frame.size.width - 4) / 4
                }
                return CGSize(width: Int(width), height: Int(height))
            }
        }
    

    and inside viewWillTransition next:

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
            if let layout = self.collectionViewLayout as? UICollectionViewFlowLayout {
                layout.invalidateLayout()
            }
    }
    

    because it works faster than without.

提交回复
热议问题