[UIView transitionFromView:toView:...]
使用布局约束的正确方法是什么?
我想在约束 toView 的超级视图中安装约束。在转换调用之前我不能这样做,因为 toView 还没有超级视图。(在调用之后但在运行循环进行之前也是如此。)等到完成块安装它意味着视图将具有动画而没有约束。
[UIView transitionFromView:toView:...]
使用布局约束的正确方法是什么?
我想在约束 toView 的超级视图中安装约束。在转换调用之前我不能这样做,因为 toView 还没有超级视图。(在调用之后但在运行循环进行之前也是如此。)等到完成块安装它意味着视图将具有动画而没有约束。
我会使用 UIViewAnimationOptionShowHideTransitionViews 选项,它允许 toView 和 fromView 在转换之前位于视图层次结构中,但显示一个并隐藏另一个。
设置toView为隐藏,添加到superview中,在transition前安装约束。然后,您可以删除完成块中的旧视图。像这样的东西:
[toView setHidden: YES];
[containerView addSubview: toView];
[containerView addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: @"|[toView]|" options: 0 metrics: nil views: NSDictionaryOfVariableBindings(containerView, toView)]];
[containerView addConstraints: [NSLayoutConstraint constraintsWithVisualFormat: @"V:|[toView]|" options: 0 metrics: nil views: NSDictionaryOfVariableBindings(containerView, toView)]];
[UIView transitionFromView: fromView toView: toView duration: 1.0 options: UIViewAnimationOptionTransitionFlipFromBottom | UIViewAnimationOptionShowHideTransitionViews completion:^(BOOL finished) {
[fromView removeFromSuperview];
}];
在转换调用之后(但在运行循环进行之前)添加约束是有效的:我之前的测试无效:-(。对不起,噪音。
NSArray *priorConstraints = _constraints;
[UIView transitionFromView:priorView
toView:newView
...
completion:^(BOOL finished) {
[_containerView removeConstraints:priorConstraints];
....
}];
_constraints = [self constrainSubview:newView toBeCongruentWithSuperview:_containerView];
- (NSArray/*[NSLayoutConstraint]*/ *)constrainSubview:(UIView *)subview
toBeCongruentWithSuperview:(UIView *)superview {
subview.translatesAutoresizingMaskIntoConstraints = NO;
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(subview);
NSArray *constraints = [NSLayoutConstraint
constraintsWithVisualFormat:@"H:-(0)-[subview]-(0)-"
options:0
metrics:nil
views:viewsDictionary];
constraints = [constraints arrayByAddingObjectsFromArray:
[NSLayoutConstraint
constraintsWithVisualFormat:@"V:-(0)-[subview]-(0)-"
options:0
metrics:nil
views:viewsDictionary]];
[superview addConstraints:constraints];
return constraints;
}