0
votes

I need to crossfade from one set of views to another set of views. There is a background sometimes behind these views. If I do a naive crossfade with animateWithDuration: v1.alpha = 1.0, v2.alpha = 0.0, then during the animation you will briefly see the background, because two views with alpha 0.5 stacked on top of each other don't have a final alpha of 1.0, they have a final alpha of I believe 0.75, hence you can see the background.

There is a UIView method transitionFromView:toView:... that allows you to achieve an ideal cross fade if you specify the animation option CrossDissolve, however, this method fails if you run two of them at once, even on fully separate views, which is a requirement. That is, if I start transitionFromView from A to B, and then transitionFromView from C to D right after, the first one will crap out.

Is there another way to achieve a proper crossfade that won't break? Does CoreAnimation have any libraries for proper crossfading? Or is there some trickery I can use to achieve it with regular UIView animations?

2

2 Answers

1
votes

I assume v1 is above v2 (after it in the subviews array if they have the same parent), and you want v1 to appear and v2 to disappear.

There's no need to animate the alpha v2 at all. Just animate the alpha of v1 from 0 to 1. When the animation ends, you can set v2's alpha to 0 if you want, and remove it from the view hierarchy.

[UIView animateWithDuration:0.2 animations:^{
    v1.alpha = 1;
} completion:^{
    v2.alpha = 0;
    [v2 removeFromSuperview];
}];
0
votes

This is how you cross dissolve between two views:

UIView.transition(from: fromView, to: toView, duration: 0.3, options: .transitionCrossDissolve) { (_ finished) in
    // Completion block here
}