[英]How to create a view controller that supports both landscape and portrait, but does not rotate between them (keeps its initial orientation)
I want to create a view controller that supports both landscape and portrait orientations, but that can not rotate between them - that is, the view should retain its original orientation. 我想创建一个既支持横向又支持纵向的视图控制器,但是不能在它们之间旋转-也就是说,视图应该保留其原始方向。
I have tried creating an ivar initialOrientation
and setting it in -viewDidAppear
with 我尝试创建一个ivar
initialOrientation
并将其设置在-viewDidAppear
中
initialOrientation = self.interfaceOrientation;
then 然后
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == initialOrientation);
}
But that causes confusing problems (presumably because -shouldAutorotateToInterfaceOrientation
is called before -viewDidAppear
). 但这会引起混乱的问题(大概是因为
-shouldAutorotateToInterfaceOrientation
在-viewDidAppear
之前被调用)。
How can I lock the orientation to its original orientation? 如何将方向锁定为其原始方向?
I was on the right track, I guess. 我猜我走在正确的轨道上。 I solved this by making
initialOrientation
a property, then setting it from the calling viewController: 我通过将
initialOrientation
设置为一个属性来解决此问题,然后通过调用viewController对其进行设置:
OrientationLockedViewController *vc = [[OrientationLockedViewController alloc] init];
vc.initialOrientation = self.interfaceOrientation;
Now I have, in OrientationLockedViewController
现在我在
OrientationLockedViewController
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == self.initialOrientation);
}
That's a bit of a weird requirement and not something I think UIKit was designed to handle. 这有点不可思议,我认为UIKit并不是要处理的。 I don't think its documented when UIKit will call
-shouldAutorotateToInterfaceOrientation
or how long it might cache those results so I see two possibilities if this behavior is important. 我不认为它在UIKit何时调用
-shouldAutorotateToInterfaceOrientation
或它可以缓存这些结果多长时间的文档中有记载,因此,如果此行为很重要,我将看到两种可能性。
Set the initialOrientiation
early, when you init your view controller if not earlier so your -shouldAutorotateToInterfaceOrientation
behavior never changes but the app will respect the orientation it started in. initialOrientiation
尽早设置initialOrientiation
,以便在不早时初始化视图控制器时使用,因此-shouldAutorotateToInterfaceOrientation
行为不会更改,但应用程序将遵循其开始的方向。
Detect the device orientation before you display this controller's view and apply your view's rotation transformation yourself. 在显示此控制器的视图之前,请先检测设备的方向,然后自己应用视图的旋转变换。 Depending on your view controller hierarchy you might need to advertise support for all rotations to allow the device to rotate and then set a transform on your view to always rotate to the same orientation regardless of the device's orientation.
根据您的视图控制器层次结构,您可能需要宣传对所有旋转的支持以允许设备旋转,然后在视图上设置一个变换以始终旋转到相同的方向,而与设备的方向无关。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.