我有一个简单的动画,我正在从旧的中心扩展一个新视图,而那个视图淡出。但是,当新视图扩展为占据整个屏幕时,此新视图(按钮和标签)的子视图从屏幕右下方“飞入”。我已尝试使用和不使用autolayout,虽然这两种情况会产生不同的结果,但它们都是错误的。
设置很简单,故事板中有两个未连接的视图控制器,并使用以下代码为视图更改设置动画:
-(void)switchViews2:(id)sender {
UIWindow *win = self.view.window;
YellowController *yellow = [self.storyboard instantiateViewControllerWithIdentifier:@"Yellow"];
yellow.view.frame = CGRectMake(0, 0, 1, 1);
yellow.view.center = self.view.center;
[win addSubview:yellow.view];
CGRect frame = self.view.frame;
[UIView animateWithDuration:5 animations:^{
yellow.view.frame = frame;
self.view.alpha = 0;
}
completion:^(BOOL finished) {
[self.view removeFromSuperview];
win.rootViewController = yellow;
}];
}
问题是,为什么子视图不会停留在超级视图内部,因为它会动画。
答案 0 :(得分:3)
要将子视图生成到位,特别是在使用Autolayout时,为变换属性而不是框架设置动画要简单得多。这样,子视图的bounds属性不会改变,因此在动画期间不需要一直传出其子视图。
使用最终帧添加子视图,将其变换设置为比例缩放仿射变换(例如0.1),然后将其设置为身份变换的动画。它将从中心点长出,所有子视图都在正确的位置。
答案 1 :(得分:1)
问题在于布局限制。如果不是在动画块中设置视图帧,而是在窗口和新视图之间添加约束,然后在动画块中调用layoutIfNeeded,它可以正常工作:
-(void)switchViews2:(id)sender {
UIWindow *win = self.view.window;
YellowController *yellow = [self.storyboard instantiateViewControllerWithIdentifier:@"Yellow"];
[yellow.view setTranslatesAutoresizingMaskIntoConstraints:NO];
yellow.view.frame = CGRectMake(0, 0, 1, 1);
yellow.view.center = self.view.center;
[win addSubview:yellow.view];
NSLayoutConstraint *con1 = [NSLayoutConstraint constraintWithItem:yellow.view attribute:NSLayoutAttributeLeading relatedBy:0 toItem:win attribute:NSLayoutAttributeLeading multiplier:1 constant:0];
NSLayoutConstraint *con2 = [NSLayoutConstraint constraintWithItem:yellow.view attribute:NSLayoutAttributeTop relatedBy:0 toItem:win attribute:NSLayoutAttributeTop multiplier:1 constant:20];
NSLayoutConstraint *con3 = [NSLayoutConstraint constraintWithItem:yellow.view attribute:NSLayoutAttributeTrailing relatedBy:0 toItem:win attribute:NSLayoutAttributeTrailing multiplier:1 constant:0];
NSLayoutConstraint *con4 = [NSLayoutConstraint constraintWithItem:yellow.view attribute:NSLayoutAttributeBottom relatedBy:0 toItem:win attribute:NSLayoutAttributeBottom multiplier:1 constant:0];
[win addConstraints:@[con1,con2,con3,con4]];
[UIView animateWithDuration:1 animations:^{
[win layoutIfNeeded];
self.view.alpha = 0;
}
completion:^(BOOL finished) {
[self.view removeFromSuperview];
win.rootViewController = yellow;
}];
}