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
initialOrientation = self.interfaceOrientation;
then
- (BOOL开发者_如何学Go)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == initialOrientation);
}
But that causes confusing problems (presumably because -shouldAutorotateToInterfaceOrientation
is called before -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:
OrientationLockedViewController *vc = [[OrientationLockedViewController alloc] init];
vc.initialOrientation = self.interfaceOrientation;
Now I have, in 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. 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.
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.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.
精彩评论