我正在使用presentViewController和自定义的modalPresentationStyle来呈现一个UIViewController,以实现Facebook POP动画过渡。
模态视图本身是完全动态的,使用代码中的Autolayout约束定义。没有xib/storyboard来支持这个模态视图。
我无法让模态视图在屏幕中间居中! Autolayout不够用,因为没有superview可以添加约束!
我的presenting代码看起来像这样(取自FB POP代码示例):
- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext
{
UIView *fromView = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey].view;
fromView.tintAdjustmentMode = UIViewTintAdjustmentModeDimmed;
fromView.userInteractionEnabled = NO;
UIView *dimmingView = [[UIView alloc] initWithFrame:fromView.bounds];
dimmingView.backgroundColor = [UIColor colorWithRed:(24/255.0) green:(42/255.0) blue:(15/255.0) alpha:1.0];
dimmingView.layer.opacity = 0.0;
UIView *toView = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey].view;
toView.frame = CGRectMake(0,
0,
CGRectGetWidth(transitionContext.containerView.bounds) - 104.f,
CGRectGetHeight(transitionContext.containerView.bounds) - 320.f);
toView.center = CGPointMake(transitionContext.containerView.center.x, -transitionContext.containerView.center.y);
[transitionContext.containerView addSubview:dimmingView];
[transitionContext.containerView addSubview:toView];
POPSpringAnimation *positionAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerPositionY];
positionAnimation.toValue = @(transitionContext.containerView.center.y);
positionAnimation.springBounciness = 10;
[positionAnimation setCompletionBlock:^(POPAnimation *anim, BOOL finished) {
[transitionContext completeTransition:YES];
}];
POPSpringAnimation *scaleAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerScaleXY];
scaleAnimation.springBounciness = 20;
scaleAnimation.fromValue = [NSValue valueWithCGPoint:CGPointMake(1.2, 1.4)];
POPBasicAnimation *opacityAnimation = [POPBasicAnimation animationWithPropertyNamed:kPOPLayerOpacity];
opacityAnimation.toValue = @(0.2);
[toView.layer pop_addAnimation:positionAnimation forKey:@"positionAnimation"];
[toView.layer pop_addAnimation:scaleAnimation forKey:@"scaleAnimation"];
[dimmingView.layer pop_addAnimation:opacityAnimation forKey:@"opacityAnimation"];
}
这个方法很好用,但是我需要动态设置实际视图大小(有时模态窗口会有四行文本和两个按钮等)。为了实现这一点,我需要在VC子类中将translatesAutoresizingMaskIntoConstraints设置为NO。这显然会使我在演示动画器中进行的框架居中失效。最终结果是一个模式窗口被卡在屏幕左边缘;奇怪的是,它在垂直方向上自己居中,但在水平方向上不居中。在视觉上,它看起来像这样(对黑色正方形感到抱歉,我必须这么做出于法律目的):
明显的解决方案是添加一个视图约束来使视图居中。没问题,对吧?
但是在哪里添加它?view.superview为空;没有父视图。我尝试创建一个自定义的"superview"属性并设置它,但是自动布局不知道如何处理在其视图层次结构之外(呈现vc)的视图。这就是我的视图层次结构的样子,注释如下:
显然不能直接访问UITransitionView。在UIWindow上设置约束无效。
有人有什么建议吗?你们如何处理这种情况?