以下是可以附加到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];
}
}];
}
}
我將代碼更改爲animation.type = kCATransitionPush;但也沒有動畫。 – 2013-04-24 02:28:01