Switch between multiple views while respecting orientation

試著忘記壹切 提交于 2019-12-06 14:38:04

When switching views directly using the first code sample the orientation can be fixed by setting the transform by hand:

- (CGAffineTransform) transformForOrientation: (UIInterfaceOrientation) io
{
    NSParameterAssert(io <= 4);
    // unknown, portrait, portrait u/d, landscape L, landscape R
    float angles[] = {0, 0, M_PI, M_PI/2, -M_PI/2};
    return CGAffineTransformMakeRotation(angles[io]);
}

- (void) switchToView: (UIView*) newView
{
    newView.transform = [self transformForOrientation:self.interfaceOrientation];
    self.view = newView;
}

Also, if you want to exchange the views during rotation, things get even more complicated. First you have to transform the incoming view according to the current one. This has to be done in the willRotate… callback:

- (void) willRotateToInterfaceOrientation: (UIInterfaceOrientation) target
         duration: (NSTimeInterval) duration
{
    incomingView = [[UIView alloc] init…];
    incomingView.transform = self.view.transform;
}

And then you switch the views in the willAnimate… callback and set the transform according to the target orientation:

- (void) willAnimateRotationToInterfaceOrientation: (UIInterfaceOrientation) io
         duration: (NSTimeInterval) duration
{
    incomingView.transform = [self transformForOrientation:io];
    self.view = incomingView;
}

This way the new view replaces the current one and rotates smoothly to the target position.

In the end I went with a “trampoline” approach. Each “skin” is a separate controller and there is a special root controller that presents the skins as modal controllers. When the skin wants to switch to a different one, it sets a flag indicating the desired next skin and dismisses itself. The root controller wakes up (viewWillAppear), notices the flag and displays the next skin.

This solution has two main advantages: 1] The controller code stays simple, as each controller displays one and only view, no view switching. 2] There is no need to hack the orientation code, because view orientation inside modally displayed controllers is handled transparently by the system.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!