这是一个可以附加到 UIViewController 的类别方法,以使用 CAAnimations 在父视图容器中的子视图之间进行转换。您可能需要根据您的目的对其进行修改,但它显示了 CATransitions 如何正确用于动画。
我写这个是为了在父 UIViewController 中创建一个来回分页效果,以便在子视图之间滑动。
- (void) transitionFromView:(UIView*)fromView
toView:(UIView*)toView
usingContainerView:(UIView*)container
andTransition:(NSString*)transitionType{
__block CGPoint targetOffset = fromView.center;
__block BOOL transitionFromSameView = [toView isEqual:fromView];
// In some cases, we want to perform the illusion of a transition when we are really just changing data in the same view.
// In those cases, we don't need to perform this position modification.
__block CGPoint centerOffset = fromView.center;
__block BOOL useAnimatedTransition = (transitionType != nil)?YES:NO;
__block BOOL isLeftToRight = ([transitionType isEqualToString:kCATransitionFromRight])?YES:NO;
if(transitionFromSameView == NO){
CGFloat horizontalOffset = (isLeftToRight == YES)?[toView sizeWidth] + 100:-([toView sizeWidth] + 100);
centerOffset = CGPointMake(fromView.center.x + horizontalOffset, fromView.center.y);
[toView setCenter:centerOffset];
[container insertSubview:toView belowSubview:fromView];
}
UIView *blockToView = toView;
UIView *blockFromView = fromView;
UIView *blockContainerView = container;
if(useAnimatedTransition == NO){
if(transitionFromSameView == NO){
[blockToView setCenter:targetOffset];
[blockFromView setCenter:centerOffset];
[blockFromView removeFromSuperview];
} else {
[blockToView setCenter:targetOffset];
[blockFromView setCenter:centerOffset];
}
} else {
[UIView animateWithDuration:kTransitionTime animations:^{
CATransition *animation = [CATransition animation];
[animation setDuration:kTransitionTime];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[animation setType:kCATransitionMoveIn];
[animation setSubtype:transitionType];
[[blockContainerView layer] addAnimation:animation forKey:@"TransitionViews"];
if(transitionFromSameView == NO){
[blockToView setCenter:targetOffset];
[blockFromView setCenter:centerOffset];
}
} completion:^(BOOL finished) {
if(transitionFromSameView == NO){
[blockFromView removeFromSuperview];
}
}];
}
}