ios - 方向锁定在 xamarin ios 中不起作用

标签 ios xamarin.ios orientation

我必须将单个 View Controller 锁定为横向,而其他 View Controller 则向所有方向旋转。我已经尝试过下面的代码。但 View 方向并没有像横向那样改变。请提出您的建议。

AppDelegate.cs

public bool RestrictRotation
{
   get;
   set;
}

[Export("application:supportedInterfaceOrientationsForWindow:")]
public UIInterfaceOrientationMask GetSupportedInterfaceOrientations(UIApplication application, IntPtr
    forWindow)
{
    if (this.RestrictRotation)
        return UIInterfaceOrientationMask.Landscape;
    else
        return UIInterfaceOrientationMask.All;
}

Viewcontroller.cs

public override void ViewDidLoad()
{
    base.ViewDidLoad();
    this.RestrictRotation(true);
    // Perform any additional setup after loading the view, typically from a nib.
}

public override bool ShouldAutorotate()
{
    return false;
}

public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations()
{
    return UIInterfaceOrientationMask.Landscape;
}

public override UIInterfaceOrientation PreferredInterfaceOrientationForPresentation()
{
    return UIInterfaceOrientation.LandscapeLeft;
}

void RestrictRotation(bool restriction)
{
    AppDelegate app = (AppDelegate)UIApplication.SharedApplication.Delegate;
    app.RestrictRotation = restriction;
}

最佳答案

您可以在ViewController中添加以下代码

public override void ViewWillAppear(bool animated)
{
   base.ViewWillAppear(animated);

   AppDelegate appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
   appDelegate.allowRotation = true;

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

public override void ViewWillDisappear(bool animated)
{
   base.ViewWillDisappear(animated);

   AppDelegate appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
   appDelegate.allowRotation = false;

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

另外,不要忘记勾选 info.plist 中的 requires full screen ,否则在某些全屏设备(如 iPad Pro)上无法使用)。

enter image description here

关于ios - 方向锁定在 xamarin ios 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59151144/

相关文章:

ios - 设置UITextField的光标位置

ios - 按钮方向问题

ios - UIImagePicker 始终以横向模式打开照片应用程序

android - ionic 状态栏问题 IOS

ios - Xcode 看不到 swift 子类

ios - NavigationLink 无法正确加载我的个人 View (SwiftUI)

ios - -[UIImage长度] : unrecognized selector sent to instance error with a NSMutableArray with Images

xamarin - 汉堡包菜单 Xamarin Forms (MasterDetailPage)

c# - 为什么导航到 View (后退按钮和 ShowViewModel)以及如何解决它之间存在差异?

iphone - presentViewController 不支持 iOS 6 中的方向