Why will the CATransition application not work if it is added to the subview layer immediately after adding the subview?

For some reason, the CAT transition will not animate if the animation is added to the subview layer immediately after adding the subview:

transitionView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; [transitionView setBackgroundColor:[UIColor redColor]]; [[self contentView] addSubview:transitionView]; CATransition *animation = [CATransition animation]; [animation setDelegate:self]; [animation setType:@"cube"]; [animation setDuration:1.0]; [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]]; [animation setSubtype:@"fromRight"]; [[transitionView layer] addAnimation:animation forKey:nil]; 

But if the animation is added after a short delay:

 transitionView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; [transitionView setBackgroundColor:[UIColor redColor]]; [[self contentView] addSubview:transitionView]; CATransition *animation = [CATransition animation]; [animation setDelegate:self]; [animation setType:@"cube"]; [animation setDuration:1.0]; [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]]; [animation setSubtype:@"fromRight"]; [self performSelector:@selector(animate) withObject:nil afterDelay:0.00001]; 

-

 - (void)animate { CATransition *animation = [CATransition animation]; [animation setDelegate:self]; [animation setType:@"cube"]; [animation setDuration:1.0]; [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]]; [animation setSubtype:@"fromRight"]; [[transitionView layer] addAnimation:animation forKey:nil]; } 

The transition will work as expected. Is there a reason for this?

+4
source share
1 answer

I also saw this behavior. I think this is because the layer is in the hierarchy of the β€œmodel” levels, which you can access, but it is not yet added to the β€œreal” data structures that display what is actually on the screen.

Anyway, you can get around this using [CATransaction flush] as follows:

 transitionView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; [transitionView setBackgroundColor:[UIColor redColor]]; [[self contentView] addSubview:transitionView]; // Synchronize the implementation details with my changes so far. [CATransaction flush]; CATransition *animation = [CATransition animation]; [animation setDelegate:self]; [animation setType:@"cube"]; [animation setDuration:1.0]; [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]]; [animation setSubtype:@"fromRight"]; [[transitionView layer] addAnimation:animation forKey:nil]; 
+8
source

Source: https://habr.com/ru/post/1399611/


All Articles