Masonary 更新约束时怎么能带上动画效果呢?

2015-05-11 12:07:46 +08:00
 xi_lin

根据文档在updateConstraints里更换了约束

- (void)updateConstraints {
if (self.isEditing) {
[self.selectedBtn mas_updateConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(20);
}];
} else {
[self.selectedBtn mas_updateConstraints:^(MASConstraintMaker *make) {
make.width.mas_equalTo(0);
}];
}
[super updateConstraints];
}

在外层调用了[view setNeedsUpdateConstraints];

结果直接就显示出来了,没有动画效果。
尝试了用animateWithDurtaion

[UIView animateWithDuration:5
animations:^{
[view setNeedsUpdateConstraints];
}];

也是不行。

应该怎么做呢?

4742 次点击
所在节点    iDev
4 条回复
vincentxue
2015-05-11 12:45:59 +08:00
https://github.com/SnapKit/Masonry/blob/master/Examples/Masonry%20iOS%20Examples/MASExampleAnimatedView.m#L105

你那个宽度用变量控制会更好。

AutoLayout 动画属于常识问题。。。
xi_lin
2015-05-11 13:17:00 +08:00
@vincentxue 感谢指教。新手上路还没有看过animation guide..

另请教一下,我看到Masonry的example里
```
// tell constraints they need updating
[self setNeedsUpdateConstraints];

// update constraints now so we can animate the change
[self updateConstraintsIfNeeded];

[UIView animateWithDuration:0.4 animations:^{
[self layoutIfNeeded];
}];
```
需要这样先setNeedsUpdateConstraints再updateConstraintsIfNeeded吗?实验了一下只执行[self setNeedsUpdateConstraints];也是可以正常更新的
vincentxue
2015-05-11 18:27:39 +08:00
@xi_lin 不客气。

这样调用是为了确保更改后的布局完成。

你可以这样理解:

setNeedsUpdateConstraints --> updateConstraintsIfNeeded --> updateConstraints。

任何布局的改变都会触发 setNeedsUpdateConstraints 方法,这个方法告诉系统这个视图布局需要更新,系统会在稍后异步调用 updateConstraintsIfNeeded。调用的时间点一般是下一次 runloop 开始。

updateConstraintsIfNeeded 方法告诉系统立即更新此视图的布局,内部调用了 updateConstraints,这里面写得是你的布局代码。

所以如果你调用了 setNeedsUpdateConstraints,相当于延迟调用了 updateConstraintsIfNeeded,相当于间接调用了 updateConstraints。

其实你直接调用 updateConstraints 也是可以的,至于为什么要有这样的一个调用顺序,这些方法内部肯定不是上面说的这么简单,系统会帮你处理很多问题,最好按照这个方法去调用就对了。
xi_lin
2015-05-11 21:25:06 +08:00
@vincentxue 感谢解释,懂了!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/190130

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX