有時我們希望 push 新頁面時採用與系統預設相反的滑動方向(例如從右側滑入)。可以透過為 UINavigationController 建立類別(Category)來實現這個自訂動畫。
#import "UINavigationController+CustomAnimation.h"
@implementation UINavigationController (CustomAnimation)
- (void)customPushViewController:(UIViewController *)viewController
{
viewController.view.frame = (CGRect){-viewController.view.frame.size.width, 0, viewController.view.frame.size};
[self.topViewController.view addSubview:viewController.view];
[UIView animateWithDuration:.35f animations:^{
viewController.view.frame = (CGRect){0, 0, self.view.bounds.size};
}];
}
@end這種做法是將新的 View 加到 self.navigationController.topViewController 上,並搭配滑動動畫。呼叫時,只要使用 customPushViewController: 取代原本的 pushViewController: 即可。
若想要在返回時也套用類似動畫,可以使用 begin/commit 動畫方式:
- (void)backToHome
{
[UIView beginAnimations:@"popView" context:NULL];
[UIView setAnimationDelegate:self];
[UIView setAnimationDuration:.5f];
[UIView setAnimationDidStopSelector:@selector(popAnimationDidStop)];
self.view.frame = CGRectMake(-CGRectGetWidth(self.view.frame), 0,
CGRectGetWidth(self.view.frame),
CGRectGetHeight(self.view.frame));
[UIView commitAnimations];
}透過以上方式,即可為 UINavigationController 的頁面推入與返回加上自訂方向與滑動動畫,讓導航過渡更具個人風格。