Monotouch – 以横向创建的视图以纵向显示

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

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

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

只是为了澄清,我的绝大多数观点都是在肖像画中。 我想以横向方向加载横向视图,而不管设备实际的方向。这可能吗? 如果是这样,我错过了什么?

提前感谢您对此事的任何帮助!

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

每次设备方向更改时都会调用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); } 

此代码仅允许视图在landscapeleft或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,一旦从堆栈中弹出这个视图,方向将恢复正常。

我认为对于你总是想要在Landscape Orientation中显示的Landscape视图,你需要在ShouldAutorotateToInterfaceOrientation中返回False或者完全删除覆盖。 这将阻止视图在设备处于纵向模式时自动旋转。