UIViewControllerのカスタム画面遷移① (モーダル遷移)
iOS7から、UIViewControllerの画面遷移を自由にカスタムできるようになりました。 今回は、UIViewControllerモーダル遷移について記載します。
遷移元ViewControllerの実装
遷移元のViewControllerにて、 UIViewControllerTransitioningDelegateを継承します。
/* アニメーションコントローラを返すメソッド(モーダルビュー表示) */ - (id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source { // UIViewControllerAnimatedTransitioningを継承したNSObjectを返す ※後述 return [[TransitionObject alloc] init]; } /* アニメーションコントローラを返すメソッド(モーダルビュー消去) */ - (id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed { // UIViewControllerAnimatedTransitioningを継承したNSObjectを返す ※後述 return [[TransitionObject alloc] init]; }
Segueを使用した画面遷移
StroryBordのSegueを利用する場合は、アクション実装箇所で下記のようにSegueの遷移を呼び出します。
(StroryBord上は、Modal
StyleのID@“TransitionSegueId”
Segueとして定義しておきます)
- (IBAction)pushButton:(id)sender { [self performSegueWithIdentifier:@“TransitionSegueId” sender:nil]; }
prepareForSegue
では、上記で実装したtransitioningDelegate
にViewControllerを指定しておきます。
※ modalPresentationStyleは、UIModalPresentationFullScreen
またはUIModalPresentationCustom
の必要があるようです。
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { ViewController *viewController = (INRegisterFeedViewController *)segue.destinationViewController; viewController.transitioningDelegate = self; viewController.modalPresentationStyle = UIModalPresentationFullScreen; }
UIViewControllerAnimatedTransitioningの実装
上記のanimationControllerForPresentedController
にて指定しているTransitionObject
オブジェクトには、下記2つのメソッドの実装が必要となります。
/** * アニメーションにかかる時間を指定 * */ - (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext { return 0.5; } /** * 画面遷移アニメーションを指定 * */ - (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext { // UIViewAnimationなどで任意のアニメーションを指定 }
これだけで簡単にオリジナルのアニメーションを実装できます。 アニメーションモデルを分離して書けるので、シンプルですね。
もっと高度なアニメーション制御もできるようなので、 色々と試してみたいと思います。