不使用UINavigationController实现Push动画

廖雪峰 / 文章 / ... / Reads: 3497 Edit

在iOS开发中,如果使用UINavigationController,配合Storyboard+Push模式的Segue,默认情况下,可以直接实现左右推出的View切换效果。

但是,如果不使用UINavigationController时,把Segue设置为Push,运行就会直接报错,而Model模式的Segue只有Cover Vertical,Flip Horizontal,Cross Dissolve和Partial Curl这4种模式,没有Push模式。

如果要在自定义的View切换动画中使用Push模式,唯一的方法是把Segue设置为Custom,然后自定义Push动画。

自定义View切换动画效果的实现方式是从UIStoryboardSegue派生一个类,然后在-(void)perform方法中自己实现动画。

经过多次Google,找到多种实现方式,经比较后发现,最简单最靠谱的Push动画实现如下:

- (void)perform
{
    UIViewController* source = (UIViewController *)self.sourceViewController;
    UIViewController* destination = (UIViewController *)self.destinationViewController;

    CGRect sourceFrame = source.view.frame;
    sourceFrame.origin.x = -sourceFrame.size.width;

    CGRect destFrame = destination.view.frame;
    destFrame.origin.x = destination.view.frame.size.width;
    destination.view.frame = destFrame;

    destFrame.origin.x = 0;
    [source.view.superview addSubview:destination.view];
    [UIView animateWithDuration:.25
                     animations:^{
                         source.view.frame = sourceFrame;
                         destination.view.frame = destFrame;
                     }
                     completion:^(BOOL finished) {
                         [source presentViewController:destination animated:NO completion:nil];
                     }];
}

以上就是从右向左切换View动画的实现,关键代码是:

sourceFrame.origin.x = -sourceFrame.size.width;

destFrame.origin.x = destination.view.frame.size.width;

将旧的View向左移动,新的View从最右开始进入。

最后,在动画结束后,手动将当前View切换到新的View:

[source presentViewController:destination animated:NO completion:nil];

因为动画效果我们已经自己实现了,所以切换到新的View就不要使用动画了。

简单修改上面的代码,就可以实现从左到右的Push切换动画:

CGRect sourceFrame = source.view.frame;
sourceFrame.origin.x = sourceFrame.size.width;

CGRect destFrame = destination.view.frame;
destFrame.origin.x = -destination.view.frame.size.width;
destination.view.frame = destFrame;

利用Custom模式的Segue,可以实现任意切换动画效果,对于简单的非3D动画,简单的几行代码即可实现。

Comments

Make a comment

Author: 廖雪峰

Publish at: ...

关注公众号不定期领红包:

加入知识星球社群:

关注微博获取实时动态: