sourcecode

Swift에서 한 뷰 컨트롤러의 방향을 세로 모드로만 잠그는 방법

codebag 2023. 5. 28. 20:46
반응형

Swift에서 한 뷰 컨트롤러의 방향을 세로 모드로만 잠그는 방법

제 앱이 모든 방향에서 지원을 받았기 때문입니다.특정 UIView 컨트롤러에 세로 모드만 잠그고 싶습니다.

예를 들어 탭 형식의 응용 프로그램이라고 가정하고 로그인 보기가 모듈식으로 나타나면 사용자가 장치를 회전하는 방식이나 현재 장치 방향에 관계없이 해당 로그인 보기만 세로 모드로 설정합니다.

여러 개의 탐색 컨트롤러 및/또는 탭 보기 컨트롤러가 있는 것과 같이 보기 계층이 복잡할 경우 상황이 상당히 복잡해질 수 있습니다.

이 구현은 App Delegate에 의존하여 하위 뷰를 반복하여 찾는 대신 개별 뷰 컨트롤러가 방향을 잠그는 시기를 설정하도록 합니다.

스위프트 3, 4, 5

AppDelegate에서 다음을 수행합니다.

/// set orientations you want to be allowed in this property by default
var orientationLock = UIInterfaceOrientationMask.all

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return self.orientationLock
}

다른 글로벌 구조자 또는 도우미 클래스에서 AppUtility를 만들었습니다.

struct AppUtility {

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

    /// OPTIONAL Added method to adjust lock and rotate to the desired orientation
    static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
   
        self.lockOrientation(orientation)
    
        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
        UINavigationController.attemptRotationToDeviceOrientation()
    }

}

그런 다음 원하는 View Controller에서 방향을 잠급니다.

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    AppUtility.lockOrientation(.portrait)
    // Or to rotate and lock
    // AppUtility.lockOrientation(.portrait, andRotateTo: .portrait)
    
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    
    // Don't forget to reset when view is being removed
    AppUtility.lockOrientation(.all)
}

iPad 또는 범용 앱인 경우

대상 설정 -> 일반 -> 배포 정보에서 "전체 화면 필요"가 선택되어 있는지 확인합니다. supportedInterfaceOrientationsFor선택하지 않으면 대리자가 호출되지 않습니다.여기에 이미지 설명 입력

스위프트 4/5

프로젝트 -> 일반 여기에 이미지 설명 입력 앱 대표자

var orientationLock = UIInterfaceOrientationMask.all
    
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    return self.orientationLock
}
struct AppUtility {
    static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
        if let delegate = UIApplication.shared.delegate as? AppDelegate {
            delegate.orientationLock = orientation
        }
    }
        
    static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
        self.lockOrientation(orientation)
        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
    }
}

보기 컨트롤러 세로 방향만 필요한 경우 다음 행을 추가합니다.세로 모드를 표시하는 데 필요한 모든 ViewController에 이 옵션을 적용해야 합니다.

override func viewWillAppear(_ animated: Bool) {
    AppDelegate.AppUtility.lockOrientation(UIInterfaceOrientationMask.portrait, andRotateTo: UIInterfaceOrientation.portrait)
}

화면 방향을 다른 사용자에게 제공합니다. 장치의 물리적 방향에 따라 컨트롤러를 봅니다.

override func viewWillDisappear(_ animated: Bool) {
    AppDelegate.AppUtility.lockOrientation(UIInterfaceOrientationMask.all)
}

스위프트 3 & 4

을 합니다.supportedInterfaceOrientations 특정 : UIView의 속성:

class MyViewController: UIViewController {

    var orientations = UIInterfaceOrientationMask.portrait //or what orientation you want
    override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
    get { return self.orientations }
    set { self.orientations = newValue }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    //...
}

갱신하다

이 솔루션은 다음과 같은 경우에만 작동합니다.viewController 포함되지 않음UINavigationController방향이 상위 뷰 컨트롤러에서 상속되기 때문입니다.
이경다음하클만를수있다의 수 .UINavigationViewController이 속성을 설정합니다.

Swift의 새 버전을 사용하려면 다음을 사용해 보십시오.

override var shouldAutorotate: Bool {
    return false
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.portrait
}

override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return UIInterfaceOrientation.portrait
}

이 코드를 추가하여 강제로 세로로 표시하고 잠급니다.

override func viewDidLoad() {
    super.viewDidLoad()

    // Force the device in portrait mode when the view controller gets loaded
    UIDevice.currentDevice().setValue(UIInterfaceOrientation.Portrait.rawValue, forKey: "orientation") 
}

override func shouldAutorotate() -> Bool {
    // Lock autorotate
    return false
}

override func supportedInterfaceOrientations() -> Int {

    // Only allow Portrait
    return Int(UIInterfaceOrientationMask.Portrait.rawValue)
}

override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {

    // Only allow Portrait
    return UIInterfaceOrientation.Portrait
}

AppDelegate에서 지원되는 설정전체 응용 프로그램이 지원할 방향에 대한 인터페이스 방향Windows용:

func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.All
} 

이것은 당신의 문제와 관련된 다른 것들에 대한 일반적인 해결책입니다.

보조 클래스 UIHelper를 만들고 다음 메서드를 적용합니다.

    /**This method returns top view controller in application  */
    class func topViewController() -> UIViewController?
    {
        let helper = UIHelper()
        return helper.topViewControllerWithRootViewController(rootViewController: UIApplication.shared.keyWindow?.rootViewController)
    }

    /**This is a recursive method to select the top View Controller in a app, either with TabBarController or not */
    private func topViewControllerWithRootViewController(rootViewController:UIViewController?) -> UIViewController?
    {
        if(rootViewController != nil)
        {
            // UITabBarController
            if let tabBarController = rootViewController as? UITabBarController,
                let selectedViewController = tabBarController.selectedViewController {
                return self.topViewControllerWithRootViewController(rootViewController: selectedViewController)
            }

            // UINavigationController
            if let navigationController = rootViewController as? UINavigationController ,let visibleViewController = navigationController.visibleViewController {
                return self.topViewControllerWithRootViewController(rootViewController: visibleViewController)
            }

            if ((rootViewController!.presentedViewController) != nil) {
                let presentedViewController = rootViewController!.presentedViewController;
                return self.topViewControllerWithRootViewController(rootViewController: presentedViewController!);
            }else
            {
                return rootViewController
            }
        }

        return nil
    }

원하는 동작으로 프로토콜을 만듭니다. 구체적인 경우는 초상화입니다.

프로토콜 방향은 초상화 {}뿐입니다.

참고: 원하는 경우 UIHelper Class 상단에 추가합니다.

View 컨트롤러 확장

당신의 경우:

class Any_ViewController: UIViewController,orientationIsOnlyPortrait {

   ....

}

앱 대리자 클래스에 다음 메서드를 추가합니다.

 func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        let presentedViewController = UIHelper.topViewController()
        if presentedViewController is orientationIsOnlyPortrait {
            return .portrait
        }
        return .all
    }

최종 참고 사항:

  • 더 많은 클래스가 세로 모드에 있는 경우 해당 프로토콜을 확장하십시오.
  • 보기 컨트롤러에서 다른 동작을 수행하려면 다른 프로토콜을 만들고 동일한 구조를 따릅니다.
  • 이 예제는 푸시 뷰 컨트롤러 후 방향 변경 문제를 해결합니다.

이 스레드에서 많은 훌륭한 답변이 있었지만, 제 요구에 맞는 답변은 없었습니다.각 탭에 탐색 컨트롤러가 있는 탭 앱이 있으며, 하나의 보기는 회전해야 하고 다른 보기는 세로로 잠겨 있어야 합니다.내비게이션 컨트롤러가 어떤 이유에서인지 하위 보기의 크기를 제대로 조정하지 않았습니다.답변과 결합하여 해결책(스위프트 3에서)을 찾았고 레이아웃 문제가 사라졌습니다.@bmjohns의 제안에 따라 구조체를 만듭니다.

import UIKit

struct OrientationLock {

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

    static func lock(to orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation: UIInterfaceOrientation) {
        self.lock(to: orientation)
        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
    }
} 

하위 클래스 UI 탭바 컨트롤러:

    import UIKit

class TabBarController: UITabBarController, UITabBarControllerDelegate {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.delegate = self
    }

    func tabBarControllerSupportedInterfaceOrientations(_ tabBarController: UITabBarController) -> UIInterfaceOrientationMask {
        if tabBarController.selectedViewController is MyViewControllerNotInANavigationControllerThatShouldRotate {
            return .allButUpsideDown
        } else if let navController = tabBarController.selectedViewController as? UINavigationController, navController.topViewController is MyViewControllerInANavControllerThatShouldRotate {
            return .allButUpsideDown
        } else {
            //Lock view that should not be able to rotate
            return .portrait
        }
    }

    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        if viewController is MyViewControllerNotInANavigationControllerThatShouldRotate {
            OrientationLock.lock(to: .allButUpsideDown)
        } else if let navController = viewController as? UINavigationController, navController.topViewController is MyViewControllerInANavigationControllerThatShouldRotate {
            OrientationLock.lock(to: .allButUpsideDown)
        } else {
            //Lock orientation and rotate to desired orientation
            OrientationLock.lock(to: .portrait, andRotateTo: .portrait)
        }
        return true
    }
}

스토리보드의 TabBar Controller 클래스를 새로 만든 하위 클래스로 변경하는 것을 잊지 마십시오.

4 12수이 있습니다. Swift 4.2(iOS 12.2)에서하십시오.UIViewController자동으로 다음을 수행해야 합니다.

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .portrait
}

.portrait부품은 유지할 방향을 알려줍니다. 원하는 대로 변경할 수 있습니다.선택할 수 있는 항목:.portrait,.all,.allButUpsideDown,.landscape,.landscapeLeft,.landscapeRight,.portraitUpsideDown.

세로 및 가로 방향의 잠금 및 변경을 위한 최적의 솔루션:

YouTube에서 이 비디오 보기:

https://m.youtube.com/watch?v=4vRrHdBowyo

이 튜토리얼은 가장 좋고 간단합니다.

또는 아래 코드를 사용합니다.

이 사진 보기

1-in second view controller에서는 가로 방향을 왼쪽으로 설정하고 first view controller에서는 portrat을 설정합니다.

2- Navigation Controller를 사용하는 경우 확장 기능을 추가해야 합니다.

import UIKit

class SecondViewController: UIViewController {


    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        UIDevice.current.setValue(UIInterfaceOrientation.landscapeLeft.rawValue, forKey: "orientation")
    }

    override open var shouldAutorotate: Bool {
        return false
    }

    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .landscapeLeft
    }

    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .landscapeLeft
    }
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
    }

//write The rest of your code in here


}

//if you use NavigationController, you should add this extension

extension UINavigationController {
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return topViewController?.supportedInterfaceOrientations ?? .allButUpsideDown
    
    }
}

가로 방향을 앱의 모든 보기로 설정하고 하나의 보기만 모든 방향으로 허용하려면(예를 들어 카메라 롤을 추가할 수 있음):

AppDelegate.swift에서 다음을 수행합니다.

var adaptOrientation = false

수신: 옵션으로 시작 완료

NSNotificationCenter.defaultCenter().addObserver(self, selector: "adaptOrientationAction:", name:"adaptOrientationAction", object: nil)

AppDelegate.swift의 다른 위치:

func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> Int {
    return checkOrientation(self.window?.rootViewController)
}

func checkOrientation(viewController:UIViewController?)-> Int{
    if (adaptOrientation == false){
        return Int(UIInterfaceOrientationMask.Landscape.rawValue)
    }else {
        return Int(UIInterfaceOrientationMask.All.rawValue)
    }
}

func adaptOrientationAction(notification: NSNotification){
    if adaptOrientation == false {
        adaptOrientation = true
    }else {
        adaptOrientation = false
    }
}

그런 다음 All Orientation을 가질 수 있는 뷰를 선택합니다.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if (segue.identifier == "YOURSEGUE") {
        NSNotificationCenter.defaultCenter().postNotificationName("adaptOrientationAction", object: nil)
    }
}

override func viewWillAppear(animated: Bool) {
    if adaptOrientation == true {
        NSNotificationCenter.defaultCenter().postNotificationName("adaptOrientationAction", object: nil)
    }
}

마지막으로 장치 방향을 선택합니다. - 세로 - 가로 왼쪽 - 가로 오른쪽

bmjohns -> 당신은 내 생명의 은인입니다.이것이 유일하게 작동하는 솔루션입니다(AppUtility 구조 사용)

이 클래스를 만들었습니다.

class Helper{
    struct AppUtility {

        static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {

            if let delegate = UIApplication.shared.delegate as? AppDelegate {
                delegate.orientationLock = orientation
            }
        }

        /// OPTIONAL Added method to adjust lock and rotate to the desired orientation
        static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {

            self.lockOrientation(orientation)

            UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
        }

    }
}

그리고 당신의 지시를 따랐고, 모든 것이 스위프트 3 -> xcode 버전 8.2.1에서 완벽하게 작동합니다.

다음을 사용하여 새 확장 작성

import UIKit

extension UINavigationController {
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
}

extension UITabBarController {
    override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
}

iOS 10과 11에서 iPad는 슬라이드 오버 및 분할 보기를 지원합니다.하려면,Requires full screen 선택 취소해야 합니다.즉, 앱이 슬라이드 오버 및 분할 보기를 지원하려면 승인된 답변을 사용할 수 없습니다.여기에서 Apple의 iPad에 멀티태스킹 기능 향상 채택에 대해 자세히 알아보십시오.

저는 (을 (1) 해제할 수 .Requires full screen(2) 구현할 기능은 하나뿐입니다.appDelegate(특히 대상 뷰 컨트롤러를 수정하고 싶지 않거나 수정할 수 없는 경우), (3) 반복 호출을 방지합니다.도우미 클래스 또는 확장이 필요하지 않습니다.

appDelegate.swift(Swift 4)

func application(_ application: UIApplication,
                 supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
    // Search for the visible view controller
    var vc = window?.rootViewController
    // Dig through tab bar and navigation, regardless their order 
    while (vc is UITabBarController) || (vc is UINavigationController) {
        if let c = vc as? UINavigationController {
            vc = c.topViewController
        } else if let c = vc as? UITabBarController {
            vc = c.selectedViewController
        }
    }
    // Look for model view controller
    while (vc?.presentedViewController) != nil {
        vc = vc!.presentedViewController
    }
    print("vc = " + (vc != nil ? String(describing: type(of: vc!)) : "nil"))
    // Final check if it's our target class.  Also make sure it isn't exiting.
    // Otherwise, system will mistakenly rotate the presentingViewController.
    if (vc is TargetViewController) && !(vc!.isBeingDismissed) {
        return [.portrait]
    }
    return [.all]
}

편집

@bmjohns는 이 기능이 iPad에서 호출되지 않는다고 지적했습니다.제가 확인해 봤는데, 네, 호출되지 않았습니다.그래서 좀 더 테스트를 해보고 몇 가지 사실을 알아냈습니다.

  1. 확인란을 선택하지 않았습니다.Requires full screeniPad에서 슬라이드 오버 및 슬라이드 보기를 활성화하고 싶기 때문입니다.를 위해서는이 Info 이를위서 Info.plist: 가에 iPad 대 의 4가지 을 모두 .Supported interface orientations (iPad).

제 앱은 페이스북과 같은 방식으로 작동합니다. 아이폰에서는 대부분 세로로 잠겨 있습니다.이미지를 전체 화면으로 볼 때 사용자가 더 잘 볼 수 있도록 가로 방향을 회전할 수 있습니다.iPad에서 사용자는 보기 컨트롤러의 모든 방향으로 회전할 수 있습니다.따라서 iPad가 스마트 커버(왼쪽 풍경)에 서 있을 때 앱이 멋져 보입니다.

  1. 가 iPad를 호출하는 application(_:supportedInterfaceOrientationsFor)Info.plist에서는 iPad에 대한 초상화만 유지합니다.앱에서 슬라이드 오버 + 보기 분할 기능이 손실됩니다.그러나 ViewController 클래스를 수정할 필요 없이 모든 뷰 컨트롤러의 방향을 한 곳에서 잠그거나 잠금 해제할 수 있습니다.

  2. 마지막으로 뷰가 표시/제거될 때 뷰 컨트롤러의 수명 주기에 따라 이 기능이 호출됩니다.다른 시간에 앱을 잠그거나 잠금을 해제하거나 방향을 변경해야 하는 경우 작동하지 않을 수 있습니다.

이에 대해 실제 테스트된 솔루션입니다.이 예에서는 전체 앱이 세로 모드여야 하지만 한 화면의 방향만 가로 모드여야 합니다.세로 모드만 선택하여 앱에 대한 세로 방향 만들기

위에서 설명한 바와 같이 AppDelegate의 코드입니다.

var orientationLock = UIInterfaceOrientationMask.all

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask 
{
  return self.orientationLock
}
struct AppUtility {  

static func lockOrientation(_ orientation: UIInterfaceOrientationMask) {
    if let delegate = UIApplication.shared.delegate as? AppDelegate {
        delegate.orientationLock = orientation
    }
}
static func lockOrientation(_ orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation:UIInterfaceOrientation) {
self.lockOrientation(orientation)     
UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
}  
}

그런 다음 가로 방향 뷰 컨트롤러가 표시되거나 푸시되기 전에 이 코드를 적어 두십시오.

override func viewWillAppear(_ animated: Bool) {  
super.viewWillAppear(animated)
AppDelegate.AppUtility.lockOrientation(UIInterfaceOrientationMask.portrait, andRotateTo: UIInterfaceOrientation.portrait)
}  

그런 다음 이 코드를 실제 뷰 컨트롤러에 기록합니다(가로 보기용).

override func viewWillAppear(_ animated: Bool) {  
super.viewWillAppear(animated)
AppDelegate.AppUtility.lockOrientation(UIInterfaceOrientationMask.landscape, andRotateTo: UIInterfaceOrientation.landscape)
}  

저는 약간의 실험을 했고 이 문제에 대한 깨끗한 해결책을 찾을 수 있었습니다.접근 방식은 뷰를 통한 뷰 태깅을 기반으로 합니다->태그

대상 ViewController에서 다음 코드 예제와 같이 루트 보기에 태그를 할당하기만 하면 됩니다.

class MyViewController: BaseViewController {

  // declare unique view tag identifier
  static let ViewTag = 2105981;

  override func viewDidLoad()
  {
    super.viewDidLoad();
    // assign the value to the current root view
    self.view.tag = MyViewController.ViewTag;
  }

마지막으로 AppDelegate.swift에서 현재 표시된 보기가 우리가 태그한 보기인지 확인합니다.

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask
{
    if (window?.viewWithTag(DesignerController.ViewTag)) != nil {
        return .portrait;
    }
    return .all;
}

이 접근 방식은 시뮬레이터를 통해 테스트되었으며 잘 작동하는 것 같습니다.

참고: 현재 MVC가 탐색 스택의 일부 하위 ViewController와 중복되는 경우에도 표시된 보기가 발견됩니다.

iOS 16의 경우 수락된 답변이 작동하지 않았지만 작동할 수 있었습니다.교체하기만 하면 됩니다.

UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")

이와 함께.

if #available(iOS 16.0, *) {
        guard
            let rootViewController = UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.rootViewController,
            let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
        else { return }
        rootViewController.setNeedsUpdateOfSupportedInterfaceOrientations()
        windowScene.requestGeometryUpdate(.iOS(
            interfaceOrientations: windowScene.interfaceOrientation.isLandscape
                ? .portrait
                : .landscapeRight
        ))
    } else {
        UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
    }

위의 @bmjohn의 답변에 감사드립니다.다음은 다른 사람들의 전사 시간을 절약하기 위해 해당 답변 코드의 작동 중인 Xamarin / C# 버전입니다.

AppDelegate.cs

 public UIInterfaceOrientationMask OrientationLock = UIInterfaceOrientationMask.All;
 public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations(UIApplication application, UIWindow forWindow)
 {
     return this.OrientationLock;
 }

정적 OrientationUtility.cs 클래스:

public static class OrientationUtility
{
    public static void LockOrientation(UIInterfaceOrientationMask orientation)
    {
        var appdelegate = (AppDelegate) UIApplication.SharedApplication.Delegate;
        if(appdelegate != null)
        {
            appdelegate.OrientationLock = orientation;
        }
    }

    public static void LockOrientation(UIInterfaceOrientationMask orientation, UIInterfaceOrientation RotateToOrientation)
    {
        LockOrientation(orientation);

        UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)RotateToOrientation), new NSString("orientation"));
    }
}

보기 컨트롤러:

    public override void ViewDidAppear(bool animated)
    {
       base.ViewWillAppear(animated);
       OrientationUtility.LockOrientation(UIInterfaceOrientationMask.Portrait, UIInterfaceOrientation.Portrait);
    }

    public override void ViewWillDisappear(bool animated)
    {
        base.ViewWillDisappear(animated);
        OrientationUtility.LockOrientation(UIInterfaceOrientationMask.All);
    }

언급URL : https://stackoverflow.com/questions/28938660/how-to-lock-orientation-of-one-view-controller-to-portrait-mode-only-in-swift

반응형