Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get final frames of subviews while in a view controller transition

I'm implementing a custom transition between view controllers in iOS 7+. In particular, I have the same button in view controller A and view controller B, the only difference is in its position (it's a little bit higher in view controller B).

I want that in the transition from view controller A to view controller B the button from A moves up so that it ends in the final position in view controller B.

Here's my animateTransition: method:

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

    UIView *containerView = [transitionContext containerView];

    [containerView insertSubview:toViewController.view belowSubview:fromViewController.view];

    UIButton *fromButton = (UIButton *)[containerView viewWithTag:1];
    UIButton *toButton = (UIButton *)[containerView viewWithTag:2];

    toButton.hidden = YES;

    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        fromButton.center = toButton.center;
    } completion:^(BOOL finished) {
        toButton.hidden = NO;
        [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
    }];
}

The problem I see is that toButton.center is NOT the correct position. It's like AutoLayout constraints have not been applied yet (I get the same frame rect as in IB). This causes that the button does not end in the correct position after the transition finishes.

Where's the error? How can I get the correct final frames of subviews from the presented view controller? If that's not possible because view controller B has not appeared yet, how can I animate subviews to achieve this effect?

like image 770
Juan Herrero Diaz Avatar asked Feb 15 '15 23:02

Juan Herrero Diaz


1 Answers

You can call layoutIfNeeded() on your toViewController's view before you start your animation. That should layout your subviews and give you the final frame for your toButton.

like image 110
user35969 Avatar answered Nov 16 '22 22:11

user35969