0
votes

I have a simple container view(green) and two sub views(red and blue) as below. Initial look

The container view is not applying auto layout and I config its size & location by frame.

While the sub views are applying auto layout(see code below)

@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;
}

Then I would like to animate the container's width change by using the CABasicAnimation as below:

- (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];
}

However, the animation is not as I would expect. I would expect the left view moves as the container's leading side and the right view does as the trailing side.

What I see is, the green view expands as expected and the left view moves as green view's leading side. However, the right view is always keeping the same distance to left view. Below is the screenshot taken at the beginning of the animation. Very beginning of the animation

Why the animation is not working as expected?