Orientation Lock

정유진·2022년 7월 15일
0

swift

목록 보기
4/24
post-thumbnail

참고 출처
https://stackoverflow.com/questions/28938660/how-to-lock-orientation-of-one-view-controller-to-portrait-mode-only-in-swift

AppDelegate

var orientationLock = UIInterfaceOrientationMask.all
    
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
	return self.orientationLock
}
  • default로 적용할 값을 선언해둔다. (.all)
  • 추후 이 값에 접근하여 화면 방향을 lock할 것이다.

Interface

struct OrientationManager {

    static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.orientationLock = orientation
        }
    }

    static func lockOrientation(_ orientation: UIInterfaceOrientationMask, rotateTo rotateOrientation:UIInterfaceOrientation) {
        self.lockOrientation(orientation)
        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
        UINavigationController.attemptRotationToDeviceOrientation()
    }

}
  • appdelegate에 접근하여 property를 수정하는 interface역할을 하는 클래스
  • orientation을 고정하는 것과 동시에 원하는 방향으로 UI 화면을 회전하는 것

공식문서 톺아보기

attemptRotationToDeviceOrientation

  • viewController의 condition이 변화하면 app은 해당 class method를 호출하고 시스템은 새로운 orientation 방향으로 회전한다.
  • iOS 16에서 deprecated 될 것
  • 대안은..?

사용하기

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        OrientationManager.lockOrientation(.landscape, andRotateTo: .landscapeRight)
    }
    
override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        OrientationManager.lockOrientation(.all)
    }
  • viewWillAppear 시점에 특정 orientation으로 lock 되도록 함수 호출
  • viewWillDisappear에서 lock을 해제한다.

사용하기 2

 if UIDevice.current.orientation == .portraitUpsideDown || UIDevice.current.orientation == .portrait {
 	AppUtility.lockOrientation(.portrait)
 } else {
 	AppUtility.lockOrientation(.landscape)
 }
  • 임의로 화면을 회전시킨다는 것은 UX적으로 바람직하지 않다고 생각되어서
  • 사용자의 현재 orientation을 고정시키는 것으로 활용하려 한다.
profile
느려도 한 걸음 씩 끝까지

0개의 댓글