Can I set maximum alpha for CATransition?

2019-09-07 07:24发布

问题:

Is it possible to adjust the maximum alpha (opacity) in a CATransition for when the views fade in and out?

What I want is something that looks like a modal segue. Compared to a default modal segue, the transition given by CATransition is very «dramatic».

Say I have two views. A: the view I want to transition from. B: the view I want to transition to.

I want B to come moving in from the bottom over A. For this I use the kCATransitionMoveIn type, with subtype kCATransitionFromTop (which is weird because B is moving up from bottom, not top).

In the default modal segue, this works fine, and A is only greyed out a little. With CATransition, A is totally black at towards the end of the transition when B has moved about 70% over A.

Code:

UIStoryboard *loginBoard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
UIViewController *vc = [loginBoard instantiateInitialViewController];

UIWindow *keyWindow = [[[UIApplication sharedApplication] delegate] window];

[keyWindow insertSubview:vc.view belowSubview:keyWindow.rootViewController.view];

CATransition *transition = [CATransition animation];
transition.duration = 0.5;
transition.type = kCATransitionMoveIn;
transition.subtype = kCATransitionFromTop;

[keyWindow.layer addAnimation:transition forKey:kCATransition];

[keyWindow.rootViewController.view removeFromSuperview];
keyWindow.rootViewController = vc;

The problem originates from here.

回答1:

After digging around some more I figured that you simply can't set a maximum opacity / alpha for the CATransition that you get out of the box.

So I solved it like this:

//offset the frame
vc.view.frame = CGRectMake(0, CGRectGetHeight(self.view.bounds), CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
[UIView animateWithDuration:5
     animations:^{
         //insert over/before root view instead of after
         [keyWindow insertSubview:vc.view aboveSubview:keyWindow.rootViewController.view];
         vc.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
         keyWindow.rootViewController.view.alpha = 0.8;
     }
     completion:^(BOOL finished) {
         NSLog(@"completed! now you can change the rootviewcontroller etc..");
     }];