简体   繁体   中英

UIView transitionWithView: animation behaviour with background color

I've set up a simple project to experiment with UIView transitionWithView: animation snippet and ran into rather odd behaviour.

在此输入图像描述

Animation works as intended only with label's text (changes it while view is halfway rotated), but the color change happens at the end of the animation, huh. Is there a way to use this kind of animation to change background colors (images?) halfway through the animation? I can build something like that myself with Core Animation, but I don't want to reinvent the wheel. I feel like I'm just not using this method correctly

Whole example code:

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (weak, nonatomic) IBOutlet UIView *innerView;
@property (weak, nonatomic) IBOutlet UILabel *label;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.innerView.layer.cornerRadius = 25.0;
    // Do any additional setup after loading the view, typically from a nib.
}

- (UIColor *)randomColor {

    CGFloat hue = ( arc4random() % 256 / 256.0 );  
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5;  
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5;  
    UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];

    return color;
}


- (IBAction)flipAction:(id)sender {

    static int i = 0;
    i++;

    [UIView transitionWithView:self.containerView
                      duration:0.5
                       options:UIViewAnimationOptionTransitionFlipFromTop
                    animations:^{

                        self.innerView.backgroundColor = [self randomColor];
                        self.label.text = [NSString stringWithFormat:@"Flip - %d", i];

                    } completion:nil];

}

@end

Sidenote. Interestingly enough, I've found that when animation options is set to UIViewAnimationOptionTransitionCrossDissolve it does the same thing, but! if you set it to 0 instead it will animate the color property through the duration. Pretty sure in that case we see implicit layer animation

在此输入图像描述

Wrap the color change line in a performWithoutAnimation block.

Why I'm guessing this works is that the transition captures a screenshot before the transition block and one after it has run. When you changed the color without performWithoutAnimation, the after screenshot won't have the changed color right away (cause it animates). With performWithoutAnimation, the after screenshot has the final color, which gets correctly captured in the after screenshot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM