UIView transitionWithView: 动画行为和背景色的动画效果

3

我建立了一个简单的项目来尝试使用UIView transitionWithView:动画片段,并遇到了奇怪的行为。

enter image description here

动画只在标签文本(在视图旋转到一半时更改)方面按预期工作,但颜色更改发生在动画结束时。有没有办法使用这种动画在动画进行到一半的时候改变背景颜色(图片)?我可以使用核心动画构建类似的东西,但我不想重复造轮子。我觉得我可能没有正确地使用这个方法。

完整的示例代码:

#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

附言。有趣的是,我发现当动画选项设置为UIViewAnimationOptionTransitionCrossDissolve时,它做了相同的事情,但是!如果你将它设置为0,它将在整个持续时间内通过动画来改变颜色属性。在这种情况下,我们几乎可以确定看到隐式层动画。

enter image description here


2
你可以将颜色变化的代码行放入一个UIView performWithoutAnimation块中,看看是否有效吗? - rounak
@rounak 哇,它真的有效! :O 如果你把这个作为答案发表,我会接受它。你能解释一下为什么它有效吗?非常感谢。 - NKorotkov
我添加了一个答案,并解释了为什么我认为这个方法有效。 - rounak
1个回答

7

将颜色变化行包装在performWithoutAnimation块中。

我猜这个方法能够起作用的原因是在转换块之前和之后,过渡会捕获屏幕截图。当你没有使用performWithoutAnimation来更改颜色时,后面的屏幕截图不会立即显示更改的颜色(因为它需要动画)。使用performWithoutAnimation后,后面的屏幕截图具有最终的颜色,并且可以正确地捕获到后面的屏幕截图。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接