iOS

기기 회전 방향, interfaceOrientation 확인하기 in iOS 13.0

삼쓰 웅쓰 2020. 7. 20. 22:28
728x90

핸드폰이 세로 방향 (portrait) 또는 가로 방향으로 (landscape) 회전할 때를 체크하려면 어떻게 해야하는지 알아보겠습니다.

아직도 구글링을 하면 예전 자료가 나오는데요,

override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
    coordinator.animate(alongsideTransition: { context in
        if UIApplication.shared.statusBarOrientation.isLandscape {
            // activate landscape changes
        } else {
            // activate portrait changes
        }
    })
}

이렇게 하면 

'statusBarOrientation' was deprecated in iOS 13.0: Use the interfaceOrientation property of the window scene instead.

라는 warning 을 만나게 됩니다. iOS 13.0 에서부터 SceneDelegate 가 추가되면서 Scene 개념이 도입되었기 때문에 현재 window scene을 이용해서 처리해라! 라는 뜻입니다.

다음과 같이 처리해주면 됩니다. windows 중에 현재 window에서 interfaceOrientation 을 뽑아서 확인할 수 있습니다.

switch로 세부적인 왼쪽 가로인지 오른쪽 가로인지, 뒤집힌 세로인지 등등 상태를 세부적으로 처리해줄 수 있습니다.
단순히 portrait, landscape만 처리하고 싶다면 isPortrait 변수로 처리해줄 수도 있습니다 :)

override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
        coordinator.animate(alongsideTransition: { context in
            guard let interfaceOrientation = UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.windowScene?.interfaceOrientation else { return }
            
            // 세부적인 처리
            switch interfaceOrientation {
                case .landscapeLeft:
                case .landscapeRight:
                case .portrait:
                case .portraitUpsideDown:
                case .unknown
            }
            
            // 단순히 가로 세로 방향만 확인하고 싶을 때
            if interfaceOrientation.isPortrait {
                print("portrait")
            } else {
                print("landscape")
            }
        })
    }

 

감사합니다!