Search code examples
objective-canimationuiviewcore-animation

ObjC - UIViews: animating view and subview independently?


I have an UIView and its subview. When I animate myView (size.x+20) my subview is being animated too, however I want to translate my subview at the same time independently(origin.x-40) (without the subview moving because of the resizing of myView).

I was able to do it by adjusting the translations (or better position, because I might wanna change y later) .fromValue, .toValue and .duration to compensate movement caused by changes to myView.

UIView beginAnimations:nil context:NULL];
[myView setFrame:pVnewFrame];
[UIView commitAnimations];

CABasicAnimation *bBTranslateAnimation = [CABasicAnimation animationWithKeyPath:@"position"]; 
bBTranslateAnimation.delegate = self;
bBTranslateAnimation.fromValue = [NSValue valueWithCGPoint:CGPointMake(160, 480)];
bBTranslateAnimation.toValue = [NSValue valueWithCGPoint:CGPointMake(160, 436)];
bBTranslateAnimation.duration = 0.35;
[buttonBar addAnimation:bBTranslateAnimation forKey:@"anim"];

But that is no proper solution. Is there a good way to move view and subviews independently? (setting autoresizeSubviews and autoresizingMask doesn't help)

Thanks in advance!


Solution

  • The way to do this is to make the two views siblings, instead of making one view a subview of the other. Just put the view that was the subview on top of the view that was the parent view, and it should look like you want it to.

    If you want the "child" view to clip to the contents of the former parent view, you might need to put the view that was the child inside a container view that is a sibling of the view that was the parent, and set the container view to opaque = no and with a clear background color. That will affect performance, however.