核心动画 returns layer 到 label 文本改变时的原始位置

Core animation returns layer to the original position when label's text is changed

我有一个简单的动画,可以移动视图的图层并保持其最终状态。

CGPoint originalPosition = self.redSquare.layer.position;
self.redSquare.layer.position   = CGPointMake(100, 100);
CABasicAnimation *animation = [[CABasicAnimation alloc]init];
animation.keyPath = @"position.x";
animation.fromValue = @(originalPosition.x);
animation.toValue = @250;
animation.duration = 2;

[self.redSquare.layer addAnimation:animation forKey:@"basic"];
self.redSquare.layer.position = CGPointMake(250, originalPosition.y);

但是当我更改标签的文本时,图层会跳转到它的原始位置。

CGPoint originalPosition = self.redSquare.layer.position;
self.redSquare.layer.position   = CGPointMake(100, 100);
CABasicAnimation *animation = [[CABasicAnimation alloc]init];
animation.keyPath = @"position.x";
animation.fromValue = @(originalPosition.x);
animation.toValue = @250;
animation.duration = 2;
animation.delegate = self;

[self.redSquare.layer addAnimation:animation forKey:@"basic"];
self.redSquare.layer.position = CGPointMake(250, originalPosition.y);

self.label.text = @"Started";

为什么会这样?

因为,当您更改文本时,视图需要重绘,

如果您启用此视图的自动布局(默认启用),它会将框架调整为自动布局。

所以有解决方案

选项 1: 禁用视图的自动布局

选项 2 说到frame changed animation,尝试给autolayout设置动画