Tim*_*Sim 12 ios autolayout swift swift2
所以我有一个容器视图(停靠在屏幕的边缘)和一个应该滑入和滑出的子视图.
func slideOut() {
UIView.animateWithDuration(Double(0.5), animations: {
self.container.bottomAnchor
.constraintEqualToAnchor(self.child.bottomAnchor).active = false
self.view.layoutIfNeeded()
})
}
func slideIn() {
UIView.animateWithDuration(Double(0.5), animations: {
self.container.bottomAnchor
.constraintEqualToAnchor(self.child.bottomAnchor).active = true
self.view.layoutIfNeeded()
})
print("numConstraints: \(container.constraints.count)")
}
Run Code Online (Sandbox Code Playgroud)
该slideIn()动画是很好,只是因为它应该是.问题是我不知道怎么做slideOut()动画.如果我只是停用NSLayoutConstraint上面的那个,那么什么都没发生.如果相反,我尝试:
self.container.bottomAnchor
.constraintEqualToAnchor(self.child.topAnchor).active = true
Run Code Online (Sandbox Code Playgroud)
再有一个自己无法同时满足的约束警告,并没有任何反应直观.此外,每当我NSLayoutConstraint激活时,约束(print(container.constraints.count))的数量都会增加,这不是一件好事.
所以我的问题是:
slideIn()在这种情况下,如何反转动画?mar*_*aie 13
该constraintEqualToAnchor方法创建一个新约束.因此,当您调用self.container.bottomAnchor.constraintEqualToAnchor(self.child.bottomAnchor)滑出功能时,您没有使用在slideIn方法中添加的约束.
要实现所需的滑出动画,您必须保留对先前约束的引用.我不确定.active在约束中设置属性的效果是什么,因为我不知道你的视图层次结构是如何设置的.但是重用约束的一种方法是将它作为VC中的var属性:
lazy var bottomConstraint:NSLayoutConstraint = self.container.bottomAnchor
.constraintEqualToAnchor(self.child.bottomAnchor)
func slideOut() {
UIView.animateWithDuration(Double(0.5), animations: {
self.bottomConstraint.active = false
self.view.layoutIfNeeded()
})
}
func slideIn() {
UIView.animateWithDuration(Double(0.5), animations: {
self.bottomConstraint.active = true
self.view.layoutIfNeeded()
})
print("numConstraints: \(container.constraints.count)")
}
Run Code Online (Sandbox Code Playgroud)
来自Apple Docs:
激活或取消激活约束会调用addConstraint:和removeConstraint:在视图上,该视图是此约束管理的项目的最近共同祖先.
因此,为什么要增加约束数量的原因是因为您不断创建新约束并通过设置active为true来添加它们.
| 归档时间: |
|
| 查看次数: |
1521 次 |
| 最近记录: |