【发布时间】:2021-11-14 05:15:48
【问题描述】:
我有一个简单的容器视图(绿色)和两个子视图(红色和蓝色),如下所示。
容器视图未应用自动布局,我按帧配置其大小和位置。
当子视图应用自动布局时(见下面的代码)
@implementation XXView {
UIView *_leftView;
UIView *_rightView;
}
- (instancetype)init {
self = [super initWithFrame:CGRectZero];
if (self) {
[self setupViewHierarchy];
[self setupConstraints];
}
return self;
}
- (void)setupViewHierarchy {
_leftView = [[UIView alloc] init];
_leftView.backgroundColor = UIColor.redColor;
_leftView.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:_leftView];
_rightView = [[UIView alloc] init];
_rightView.backgroundColor = UIColor.blueColor;
_rightView.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:_rightView];
self.backgroundColor = UIColor.greenColor;
}
- (void)setupConstraints {
[NSLayoutConstraint activateConstraints:@[
[_leftView.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:10],
[_leftView.topAnchor constraintEqualToAnchor:self.topAnchor],
[_leftView.bottomAnchor constraintEqualToAnchor:self.bottomAnchor],
[_leftView.widthAnchor constraintEqualToConstant:50],
[_rightView.trailingAnchor constraintEqualToAnchor:self.trailingAnchor constant:-10],
[_rightView.topAnchor constraintEqualToAnchor:_leftView.topAnchor],
[_rightView.bottomAnchor constraintEqualToAnchor:_leftView.bottomAnchor],
[_rightView.widthAnchor constraintEqualToAnchor:_leftView.widthAnchor],
]];
}
...
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
XXView *tv = [[XXView alloc] init];
CGFloat width = self.view.bounds.size.width;
tv.frame = CGRectMake(50, 400, width-100, 100);
[self.view addSubview:tv];
self.tv = tv;
}
然后我想使用 CABasicAnimation 为容器的宽度变化设置动画,如下所示:
- (void)startAnimation {
[CATransaction begin];
CGFloat width = self.bounds.size.width;
CABasicAnimation *widthAnimation = [CABasicAnimation animationWithKeyPath:@"bounds.size.width"];
widthAnimation.fromValue = @(width/2);
widthAnimation.toValue = @(width);
widthAnimation.duration = 1;
[self.layer addAnimation:widthAnimation forKey:@"123"];
[CATransaction commit];
}
然而,动画并不像我想象的那样。我希望左视图作为容器的前端移动,而右视图作为尾端移动。
我看到的是,绿色视图按预期扩展,左视图作为绿色视图的前侧移动。但是,右视图始终与左视图保持相同的距离。下面是动画开始时的截图。
为什么动画没有按预期工作?
【问题讨论】:
标签: ios animation autolayout