標籤: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動畫