How to lock orientation of one view controller to portrait mode only in Swift

后端 未结 16 2054
梦谈多话
梦谈多话 2020-11-22 12:07

Since my app got support for all orientation. I would like to lock only portrait mode to specific UIViewController.

e.g. assume it was Tabbed Application and when Si

16条回答
  •  抹茶落季
    2020-11-22 12:43

    Thanks to @bmjohn's answer above. Here is a working Xamarin / C# version of the that answer's code, to save others the time of transcription:

    AppDelegate.cs

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

    Static OrientationUtility.cs class:

    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"));
        }
    }
    

    View Controller:

        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);
        }
    

提交回复
热议问题