iOS8中UIViewController中新增presentationController属性,
@property (nonatomic,readonly) UIPresentationController *presentationController NS_AVAILABLE_IOS(8_0);
当我们需要modal一个控制器的时候,例如A->B,我们可以自定义B控制器modal的样式,也可以使用系统提供的modal样式
如果要系统的modal样式,只需要设置B控制器的modalPresentationStyle就可以了.如果要自定义modal样式,则需要设置B控制器的modalPresentationStyle为UIModalPresentationCustom;
这样系统就知道,modal出B控制器的时候要使用自定义的modal样式
modal出B控制器的样式是通过B控制器询问自身的属性--transitioningDelegate得到的
@property (nonatomic,assign) id <UIViewControllerTransitioningDelegate> transitioningDelegate NS_AVAILABLE_IOS(7_0);
可以看到transitioningDelegate只是一个遵守<UIViewControllerTransitioningDelegate>协议的对象
首先B控制器会调用delegate下面这个方法,询问transitioningDelegate应该用哪一个PresentationController来控制modal
- (UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source NS_AVAILABLE_IOS(8_0);
然后B控制器会询问transitioningDelegate,自己modal出来和dismiss消失的时候要以怎样的方式(自己写动画)进行
- (id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source; - (id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed;
从代码可以看出,控制modal和dismiss动画的是一个遵守UIViewControllerAnimatedTransitioning协议的对象
这个协议很简单,第一个是modal或者dismiss完成的时间,第二个是B控控制器modal或者dismiss时通知delegate的方法,动画要写在这里面,通过transitionContext取出相应的View,添加动画,第三个方法会在[transitionContext completeTransition:]调用后被系统调用
// This is used for percent driven interactive transitions, as well as for container controllers that have companion animations that might need to // synchronize with the main animation. - (NSTimeInterval)transitionDuration:(id <UIViewControllerContextTransitioning>)transitionContext; // This method can only be a nop if the transition is interactive and not a percentDriven interactive transition. - (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext; @optional // This is a convenience and if implemented will be invoked by the system when the transition context's completeTransition: method is invoked. - (void)animationEnded:(BOOL) transitionCompleted;
如果要添加一个自定义的CView,将CView添加到A.view上,将B.view添加到CView上,以这种方式展Modal出B的时候,可以将CView写在UIPresentationController里面,
如果还要给CView添加动画的话,可以用transitionCoordinator来执行动画
id<UIViewControllerTransitionCoordinator> transitionCoordinator = self.presentingViewController.transitionCoordinator;
下面附上demo一个~~~~https://github.com/yang7/zxyPresentationController