I'm facing a very annoying problem. Here's the context : I have a "rectangle" view which is the subview of the main view. What i'm trying to do is simple, when I click on a button, I want the "rectangle" view to translate on the x-axis in order to disappear. I then add a new subview and translate it in order to take the place of the previous "rectangle" view. It's work fine except that if I press the button again, the animation will begin off the screen, like the CGAffineTransformMakeTranslation didn't change the frame of my new "rectangle" view. Here's the code :
UIView *rectangleView = [detailView viewWithTag:4]; //the actual frame is (20.0, 30.0, 884.0, 600.0)
[UIView animateWithDuration:0.5 animations:^{
[rectangleView setTransform:CGAffineTransformMakeTranslation(-1000, 0)];
} completion:^(BOOL finished) {
[rectangleView removeFromSuperview];
UIView *otherView = [[UIView alloc] initWithFrame:CGRectMake(1020.0, 30.0, 884.0, 600.0)];
[otherView setBackgroundColor:[UIColor purpleColor]];
[otherView setTag:4];
[detailView addSubview:otherView];
[UIView animateWithDuration:0.5 animations:^{
[otherView setTransform:CGAffineTransformMakeTranslation(-1000, 0)];
} completion:^(BOOL finished) {
[otherView release];
}];
}];
After your second view is added you already set its transform to be equal to CGAffineTransformMakeTranslation(-1000, 0)
, and when you want to remove that view you set exactly the same transform - so it will have no effect. You have 2 options here:
Apply translation to the transform the view already has:
CGAffineTransform newTransform = CGAffineTransformConcat(rectangleView.transform, CGAffineTransformMakeTranslation(-1000, 0));
[rectangleView setTransform:newTransform];
Instead of applying transforms operate with view position directly (e.g. via its center property)
UIView *rectangleView = [detailView viewWithTag:4]; //the actual frame is (20.0, 30.0, 884.0, 600.0)
CGAffineTransform tf = CGAffineTransformMakeTranslation(-1000, 0);
[UIView animateWithDuration:0.5 animations:^{
[rectangleView setCenter: CGPointApplyAffineTransform(rectangleView.center, tf)];
} completion:^(BOOL finished) {
[rectangleView removeFromSuperview];
UIView *otherView = [[UIView alloc] initWithFrame:CGRectMake(1020.0, 30.0, 884.0, 600.0)];
[otherView setBackgroundColor:[UIColor purpleColor]];
[otherView setTag:4];
[detailView addSubview:otherView];
[UIView animateWithDuration:0.5 animations:^{
[otherView setCenter: CGPointApplyAffineTransform(otherView.center, tf)];
} completion:^(BOOL finished) {
[otherView release];
}];
}];