在UIViewControllerContextTransitioning animateTransition中移动时,UIView框架会重置:

时间:2015-01-17 19:58:27

标签: ios objective-c

我在视图控制器中间有一个正方形。我想为它设置动画并将其移动到新的视图控制器。但是,当我这样做时,它会重置为(0,0)。有什么建议吗?

-(void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {

    //pointers to VCs
    PresentingViewController *fromVC = (PresentingViewController*)[transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    PresentedViewController *toVC = (PresentedViewController*)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

    //add to view
    [transitionContext.containerView addSubview:toVC.view];

    //make to view transparent
    UIColor *oldColor = toVC.view.backgroundColor;
    toVC.view.backgroundColor = [UIColor clearColor];

    //move square to new VC
    CGRect oldFrame = fromVC.square.frame;
    [toVC.view addSubview:fromVC.square];
    fromVC.square.frame = oldFrame; //view appears at 0,0 instead of the center. why???

    //animate expand and color change
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        fromVC.view.tintAdjustmentMode = UIViewTintAdjustmentModeDimmed;
        toVC.view.backgroundColor = oldColor;
        fromVC.square.transform = CGAffineTransformScale(fromVC.square.transform, 1.5, 1.5);


    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.2 animations:^{

        } completion:^(BOOL finished) {
            [transitionContext completeTransition:YES];

        }];
    }];
}

2 个答案:

答案 0 :(得分:3)

问题是这个子视图可能有定义的约束(您明确定义的那些或Interface Builder自动添加的约束),当您将其移动到目标视图控制器的视图时,它可以&#39 ; t找到约束,因此frame由自动布局模糊地定义。

您可以在新家中添加此子视图位置的约束,也可以将translatesAutoresizingMaskIntoConstraints设置为TRUE,并从constraints定义frame }和autoresizingMask将视图保留在新位置。

答案 1 :(得分:2)

在自定义过渡动画中对抗自动布局非常令人沮丧。我的建议是不对子视图的帧进行动画处理,而是为子视图的变换设置动画,将其更改为平移变换。例如,在动画块中使用以下内容:

subview.transform = CGAffineTransformMakeTranslation(0, -40)

然后,在完成块中,如果您需要设置子视图的位置,则可以使用标识转换。

subview.transform = CGAffineTransformIdentity

这种方法效果很好,因为它不会改变子视图的帧,这可能导致自动布局将其设置回来。