개발

iOS Swift를 이용하여 화면 회전에 대한 이벤트 받기

소소ing 2021. 6. 14. 18:57
반응형

특정 화면에서 화면 회전에 대한 이벤트를 받으려면 어떻게 해야 할까?

- 앱에서 화면 회전이 가능하나 iPhone의 세로보기 잠금을 해 놓은 상태라도 iPhone을 가로로 돌릴경우 이벤트는 발생된다.

 

1. NotificationCenter를 이용하여 Observer를 구성한다. 

// 아래 코드를 viewDidAppear 에 작성한다.

//  - 여기서 detectOrientation은 화면 회전 이벤트 발생시 호출할 함수 이다.

NotificationCenter.default.addObserver(self, selector: #selector(self.detectOrientation), name: NSNotification.Name("UIDeviceOrientationDidChangeNotification"), object: nil)

 

 

2. 해당 ViewController에서 나갈때 add 한 Observer를 해제 시켜 주어야 한다.

// 아래 코드를 viewDidDisappear 에 작성한다.

NotificationCenter.default.removeObserver(self, name: NSNotification.Name("UIDeviceOrientationDidChangeNotification"), object: nil)


3. 화면 회전 탐지시 호출되는 함수에서 아래와 같이 화면 회전에 대한 탐지가 가능하다. 

@objc func detectOrientation() {

        if (UIDevice.current.orientation == .landscapeLeft) || (UIDevice.current.orientation == .landscapeRight) {

            print("detectOrientation : landscapeLeft")         

        }

        // iPhone X 이후 노출 디자인 단말에서 portraitUpsideDown 회전은 지원되지 않으니 참조!

         else if (UIDevice.current.orientation == .portrait) || (UIDevice.current.orientation == .portraitUpsideDown){

            print("detectOrientation : portrait")

        }

}

반응형