Search code examples
iosuiviewcontrollermodalviewcontrollercustom-transition

Present a transparent modal UIViewController


I'm trying to make a custom alertView (for iOS7+) on my own but I struggle with the alertView presentation.

I have a UIViewController with a black background (alpha set to 0.25f), and a alertView as subview.

When I want to show the alertView, I present modally the viewController:

-(void) show 
{
    UIWindow* window = [[UIApplication sharedApplication] keyWindow];
    self.modalTransitionStyle = UIModalPresentationCustom;
    self.transitioningDelegate = self;
    [window.rootViewController presentViewController:self animated:YES completion:nil];
}

And here is my animator object:

-(NSTimeInterval) transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
{
    NSLog(@"%s",__PRETTY_FUNCTION__);
    return 2;
}

-(void) animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    NSLog(@"%s",__PRETTY_FUNCTION__);

    UIView* toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    toView.alpha = 0;

    UIView* container = [transitionContext containerView];
    [container addSubview:toView];

    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        toView.alpha = 0.5;
    } completion:^(BOOL finished) {
        [transitionContext completeTransition:YES];
    }];
}

The thing is: the modal VC is fading with the presenting VC in background as its supposed to do, but when the animation ends the presenting VC is removed from the background.

If I call [transitionContext completeTransition:YES]; instead, the presenting VC is in background but the modal VC is removed at animation end, so I guess the context cancels the presentation if we send 'NO'.

Is there a way to keep the presenting VC in background without having to make a snapshot of it and set it as background of the modal VC's view?


Solution

  • For your information, I finally made my custom alertView a subclass of UIView for the "popUp part". To show it, I just add the alertView as subview of the keyWindow with the constraints to center it, and put a transparent black background view behind it.

    As it's not a controller, I have to manage UI rotation by myself (only for iOS 7, it rotates well with the UI in iOS 8).