iOS 不使用UINavigationController實現Push動畫

來源:互聯網
上載者:User

標籤:ios   開發   設定   模式   效果   

轉自廖雪峰

在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動畫,簡單的幾行代碼即可實現。

iOS 不使用UINavigationController實現Push動畫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.