Detecting iOS UIDevice orientation

后端 未结 8 935
一生所求
一生所求 2020-11-28 03:29

I need to detect when the device is in portrait orientation so that I can fire off a special animation. But I do not want my view to autorotate.

How do I override a

8条回答
  •  青春惊慌失措
    2020-11-28 04:06

    .UIDeviceOrientationDidChange notification is called many times on iphone even when device did not rotate. Do not know the reason, but if you need it only when device really rotated, then do the following.

    NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged), name: .UIDeviceOrientationDidChange, object: nil)
    

    The method called from observer should look like this:

    func orientationChanged() {
    
        if traitCollection.isIphone {
    
            defer {
                self.previousTraitCollectionForIphone = traitCollection
            }
    
            guard let previousTraitCollectionForIphone = previousTraitCollectionForIphone else {
    
                updateView()
                return
            }
    
            if previousTraitCollectionForIphone != traitCollection {
                updateView()
            }
    
        } else {
            updateView()
        }
    }
    

提交回复
热议问题