특정 화면 세로고정 하기

zoe·2021년 12월 13일
0

IOS

목록 보기
2/2

앱 전체 화면 회전을 설정하는 방법

Project Target에서 설정해주면 Info.plist에 자동으로 반영된다

특정 뷰 컨트롤러를 세로고정 하는 방법

방법1. AppDelegate 사용하기

application(_:supportedInterfaceOrientationsFor:) 로 설정하기

  1. AppDelegate에 아래 코드를 추가한다
var supportOnlyPortrait = true
    
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        if (supportOnlyPortrait == false) {
            return UIInterfaceOrientationMask.allButUpsideDown
        }
        return UIInterfaceOrientationMask.portrait
    }
  1. 세로로만 구현할 뷰컨에 아래 코드를 추가한다
let appDelegate = UIApplication.shared.delegate as! AppDelegate
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        appDelegate.supportOnlyPortrait = true
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        appDelegate.supportOnlyPortrait = false
    }

적용한 모습

가로로 눕혀도 화면 보기가 세로로 고정된다

단점

전역변수를 선언해야 해서 부담이 된다

방법2. viewController 내부에서 설정하기

supportedInterfaceOrientations 를 이용하기

  • 이 프로퍼티는 뷰컨트롤러가 지원하는 방향을 의미한다
  • 원하는 값을 리턴해주면 된다
    • 세로고정 하고싶으면 .portrait 을 반환한다

둘 다 가능하게 하려면 이렇게 배열에 담아서 리턴하면 된다

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return [.portrait, .landscapeLeft]
    }

주의해야 하는 경우

이렇게 고정하고 싶은 뷰컨트롤러가 네비게이션 컨트롤러 같은 상위뷰컨트롤러를 가지는 경우

아무리 supportedInterfaceOrientations 프로퍼티를 재정의 해줘도 세로고정이 안된다.
왜냐하면 상위뷰컨의 세팅을 따르기 때문이다
*(참고로supportedInterfaceOrientations 의 default가 .all 이다)

해결방법

  1. navigationController 에서 supportedInterfaceOrientations를 아래처럼 재정의 해준다
class NavigationController: UINavigationController {
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        topViewController?.supportedInterfaceOrientations ?? .all
    }
}
  1. 그리고 원하는 뷰컨에서 .portrait 을 반환해주면 해당 뷰컨에서만 세로고정이 된다
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }

이런식으로 view controller마다 프로퍼티를 재정의해서 지원하는 방향을 설정할 수 있다

회전여부를 결정하는 방법

회전 여부를 결정하기 위해 시스템은 뷰컨트롤러가 지원되는 방향앱이 지원하는 방향을 비교한다.
앱이 지원하는 방향은 Info.plist 파일 또는 AppDelegate의 메서드인application(_:supportedInterfaceOrientationsFor:) 에 의해 결정된다

그 순서는 일단 Info.plist 에 있는 값을 기본으로 사용하고,application(_:supportedInterfaceOrientationsFor:) 메서드가 정의 되었다면 해당 메서드를 따른다.

관련 프로퍼티

  • shouldAutorotate
    이 프로퍼티가 True 일때만 메서드들을 호출한다고 한다. 우리가 핸드폰에서 설정하는 자동회전 설정을 의미하는 것 같다

참고
오동나무 블로그 https://odong-tree.github.io/ios/2020/12/27/supportedInterfaceOrientations/
라자냐 블로그 https://velog.io/@wonhee010/특정-ViewController에서-화면-회전-처리

profile
개발하면서 마주친 문제들을 정리하는 공간입니다.

0개의 댓글