Swift - How to detect orientation changes

后端 未结 13 1804
余生分开走
余生分开走 2020-11-29 19:49

I want to add two images to single image view (i.e for landscape one image and for portrait another image)but i don\'t know how to detect orientation changes using swift lan

13条回答
  •  萌比男神i
    2020-11-29 20:47

    You can use viewWillTransition(to:with:) and tap into animate(alongsideTransition:completion:) to get the interface orientation AFTER the transition is complete. You just have to define and implement a protocol similar to this in order to tap into the event. Note that this code was used for a SpriteKit game and your specific implementation may differ.

    protocol CanReceiveTransitionEvents {
        func viewWillTransition(to size: CGSize)
        func interfaceOrientationChanged(to orientation: UIInterfaceOrientation)
    }
    
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
            super.viewWillTransition(to: size, with: coordinator)
    
            guard
                let skView = self.view as? SKView,
                let canReceiveRotationEvents = skView.scene as? CanReceiveTransitionEvents else { return }
    
            coordinator.animate(alongsideTransition: nil) { _ in
                if let interfaceOrientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation {
                    canReceiveRotationEvents.interfaceOrientationChanged(to: interfaceOrientation)
                }
            }
    
            canReceiveRotationEvents.viewWillTransition(to: size)
        }
    

    You can set breakpoints in these functions and observe that interfaceOrientationChanged(to orientation: UIInterfaceOrientation) is always called after viewWillTransition(to size: CGSize) with the updated orientation.

提交回复
热议问题