【问题标题】:Monotouch - View created in landscape orientation is displayed in portrait orientationMonotouch - 以横向创建的视图以纵向显示
【发布时间】:2023-12-04 18:48:01
【问题描述】:

我创建了一个视图控制器并将视图的方向设置为 XCode 4.2 (Interface Builder) 中的横向。但是,当我添加视图时,视图以纵向显示。我已经在所有视图控制器中覆盖了 ShouldAutorotateToInterfaceOrientation 以返回 true,并且我尝试使用以下代码手动旋转视图:

this.View.Transform.Rotate (3.14f * .5f);

我也尝试将框架设置为横向框架(即 480 X 320),尽管视图的框架已正确设置。

澄清一下,我的绝大多数观点都是纵向的。我想以横向加载横向视图,无论设备实际处于什么方向。这可能吗?如果是这样,我错过了什么?

提前感谢您在此问题上的任何帮助!

更新:我注意到 ShouldAutorotateToInterfaceOrientation 仅在加载视图时调用一次。旋转设备时不会调用它。这是正常行为吗?

【问题讨论】:

  • 当你说你已经覆盖了 ShouldAutorotateToInterfaceOrientation 以返回 true...你的意思是你正在返回以下内容吗?: return toInterfaceOrientation == UIInterfaceOrientation.LandscapeLeft || toInterfaceOrientation == UIInterfaceOrientation.LandscapeRight;

标签: ios xamarin.ios


【解决方案1】:

每次设备方向改变时都会调用ShouldAutorotateToInterfaceOrientation。

public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
        {
            Console.Out.WriteLine(toInterfaceOrientation.ToString());
            // Return true for supported orientations

            // This particular screen is landscape only!
            return (toInterfaceOrientation == UIInterfaceOrientation.LandscapeLeft || toInterfaceOrientation == UIInterfaceOrientation.LandscapeRight);
        }

此代码仅允许视图在横向左或横向模式下定向,并且每次都将新的设备方向写入控制台。

当您加载视图并将其推送到(例如)UINavigationController 时,它仍处于纵向模式(并且不会调用 ShouldAutorotateToInterfaceOrientation。)

在 Objective-C 中,强制设备方向相当容易,但在 MonoTouch 中,似乎没有直接映射。

解决方案;

向 Objective-C 运行时发送消息,指定我们想要的方向。

您可以通过将以下内容添加到视图控制器来轻松做到这一点:

Selector orientationSetter;

        private void SetOrientation (UIInterfaceOrientation toOrientation)
        {
            if (orientationSetter == null)
            {
                orientationSetter = new Selector ("setOrientation:");
            }

            Messaging.void_objc_msgSend_int (UIDevice.CurrentDevice.Handle,
            orientationSetter.Handle, (int)toOrientation);
        }

您现在可以手动更改整个设备的方向。 更重要的是,如果你使用 UINavigationController,一旦这个视图从堆栈中弹出,方向就会恢复正常。

【讨论】:

    【解决方案2】:

    我认为,对于您始终希望在 Landscape Orientation 中显示的 Landscape 视图,您需要在 ShouldAutorotateToInterfaceOrientation 中返回 False 或完全移除覆盖。当设备处于纵向模式时,这将防止视图自动旋转。

    【讨论】:

    • 我已经为 ShouldAutorotateToInterfaceOrientation 尝试了所有不同的选项(返回 true,返回 false,一起删除),并且行为没有改变。问题不在于阻止自动旋转。视图根本不旋转。它只是以纵向显示。 XCode 4.2(界面生成器)中视图的“模拟指标”下的“方向”选项是否指示视图应显示在哪个方向,还是我需要做其他事情来获得旋转方向?
    • 模拟指标中的任何设置都不会在运行时影响 UI,它们只会显示“假设”。这里有一个想法:您是否在 Mono 项目设置中表明您支持所有设备方向?打开您的项目设置,展开构建,然后转到 iPhone 应用程序区域。在那里,您将找到您的应用支持的方向列表。确保它们都被选中,然后恢复 ShouldAutorotateToInterfaceOrientation 覆盖并返回 true。
    • 感谢主管技术,但仍然没有任何变化。我认为指定一个方向是微不足道的,但显然,我错了。我是否还应该通过 this.View.Transform.Rotate(3.14f * 0.5f) 旋转视图?虽然这条线似乎没有任何影响。