-(void)updateConstraints 中的动画约束变化
Animating Constraint Changes in -(void)updateConstraints
我读过很多问题,这些问题说明为了动画化约束变化,我们只需要...
self.someConstraint.constant = 0.f;
[UIView animateWithDuration:0.5f animations:^{
[self layoutIfNeeded];
}];
最近,我读到自定义视图子类应该在 UIView 上使用 -(void)updateConstraints
方法来执行约束更新,以防发生许多 属性 更改,这会导致您这样做上面的代码块在多个地方,这将导致许多不需要的布局传递。
UIView -(void)updateConstraints documentation
我真的很喜欢这种更新所有约束的方法。一些简单的代码...
- (void)updateConstraints
{
if(someCondition)
{
self.someConstraint.constant = 0.f;
}
//Maybe some other conditions or constant changes go
here based on the current state of your view.
[super updateConstraints];
}
至此,我原来的约束动画代码现在只变成了
[self setNeedsUpdateConstraints];
唯一的问题是我现在失去了动画这些变化的能力。
我查看了视图文档以找到一种方法来为约束的这些更改设置动画,但我似乎找不到合适的方法来覆盖以在动画块中调用 [self layoutIfNeeded]
。即使在这种情况下,我也觉得应该没有必要调用它,因为将要执行布局,我觉得我不应该当场强制执行它。
有谁知道如何使这些约束更改具有动画效果?
您需要致电[self updateConstraintsIfNeeded]
。所以你的代码看起来像这样...
[self updateConstraintsIfNeeded];
[UIView animateWithDuration:0.25 animations:^{
[self layoutIfNeeded];
}];
我读过很多问题,这些问题说明为了动画化约束变化,我们只需要...
self.someConstraint.constant = 0.f;
[UIView animateWithDuration:0.5f animations:^{
[self layoutIfNeeded];
}];
最近,我读到自定义视图子类应该在 UIView 上使用 -(void)updateConstraints
方法来执行约束更新,以防发生许多 属性 更改,这会导致您这样做上面的代码块在多个地方,这将导致许多不需要的布局传递。
UIView -(void)updateConstraints documentation
我真的很喜欢这种更新所有约束的方法。一些简单的代码...
- (void)updateConstraints
{
if(someCondition)
{
self.someConstraint.constant = 0.f;
}
//Maybe some other conditions or constant changes go
here based on the current state of your view.
[super updateConstraints];
}
至此,我原来的约束动画代码现在只变成了
[self setNeedsUpdateConstraints];
唯一的问题是我现在失去了动画这些变化的能力。
我查看了视图文档以找到一种方法来为约束的这些更改设置动画,但我似乎找不到合适的方法来覆盖以在动画块中调用 [self layoutIfNeeded]
。即使在这种情况下,我也觉得应该没有必要调用它,因为将要执行布局,我觉得我不应该当场强制执行它。
有谁知道如何使这些约束更改具有动画效果?
您需要致电[self updateConstraintsIfNeeded]
。所以你的代码看起来像这样...
[self updateConstraintsIfNeeded];
[UIView animateWithDuration:0.25 animations:^{
[self layoutIfNeeded];
}];