如何动画有约束的UIView?
问题描述:
我有两个UIViews
我想在屏幕上动画和关闭。两者都应该从屏幕开始定位。顶部向下动画,底部向上。没有限制,它按预期工作。但是,在应用程序启动时可以看到UIViews
(可以看到轻微的动画)。尽管如此,他们在屏幕上做动画。如何动画有约束的UIView?
顶部UIView
,我有一个领先的空间,尾部空间,顶部空间和高度。
对于底部UIView
,我有一个领先的空间,拖尾空间,底部空间和高度。
我应该如何调整我的代码和/或约束以获得所需的动画?
这里是我的代码:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[self animateViewsIn];
}
- (void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
self.topView.frame = CGRectMake(16.0, -self.topView.frame.size.height, self.topView.frame.size.width, self.topView.frame.size.height);
self.bottomView.frame = CGRectMake(16.0, self.view.bounds.size.height, self.bottomView.frame.size.width, self.bottomView.frame.size.height);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)animateViewsIn {
[UIView animateWithDuration:0.5
delay:1.0
options: UIViewAnimationOptionCurveEaseIn
animations:^{
self.topView.frame = CGRectMake(16.0,
self.topView.frame.size.height/8.0, self.topView.frame.size.width,
self.topView.frame.size.height);
self.bottomView.frame = CGRectMake(16.0, (self.view.bounds.size.height-self.bottomView.frame.size.height)-20.0, self.bottomView.frame.size.width, self.bottomView.frame.size.height);
}
completion:^(BOOL finished){
NSLog(@"Done!");
}];
}
- (IBAction)animateViewsOut:(id)sender {
CGRect basketTopFrame = self.topView.frame;
basketTopFrame.origin.y = -basketTopFrame.size.height;
CGRect basketBottomFrame = self.bottomView.frame;
basketBottomFrame.origin.y = self.view.bounds.size.height;
[UIView animateWithDuration:0.5
delay:1.0
options: UIViewAnimationOptionCurveEaseOut
animations:^{
[self.view layoutIfNeeded];
self.topView.frame = basketTopFrame;
self.bottomView.frame = basketBottomFrame;
}
completion:^(BOOL finished){
NSLog(@"Done!");
}];
}
答
当使用约束,你不应该调整帧。您应该修改约束的constant
属性(或者取消一个约束并激活另一个约束)。
下面是从顶部动画的顶视图的一个例子,假设你加入@IBOutlet
称为topConstraint
到视图topView
的顶部约束:
在Objective-C:
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
self.topConstraint.constant = -self.topView.frame.size.height; // or whatever you want
[self.view layoutIfNeeded];
[UIView animateWithDuration:0.5 delay:1 options:0 animations:^{
self.topConstraint.constant = 0;
[self.topView layoutIfNeeded];
} completion:nil];
}
在斯威夫特:
override func viewDidAppear(_ animated: Bool) {
topConstraint.constant = -topView.frame.height // or whatever you want
view.layoutIfNeeded()
UIView.animate(withDuration: 0.5, delay: 1, animations: {
topConstraint.constant = 0
self.view.layoutIfNeeded()
})
}
当使用约束时,你不应该调整帧。您应该修改约束的“常量”属性(或者取消一个约束并激活另一个约束)。可能的重复https://*.com/a/28329399/1271826(tho,坦率地说Swift的答案;这个想法在Objective-C中是相同的)。或者这里是Objective-C的答案,它说明了约束的动画:https://*.com/a/14190042/1271826。 – Rob
谢谢Rob。我已经添加了通过IBOutlet连接的约束,并使用常量来动画它们,但是如何在屏幕外启动UIView? –
leftConstraint.constant - 320.是一个示例如何开始离屏。 – GeneCode