gpt4 book ai didi

ios - 添加、重用和删除 NSLayoutAnchors

转载 作者:IT王子 更新时间:2023-10-29 05:30:36 26 4
gpt4 key购买 nike

所以我有一个容器 View (停靠在屏幕边缘)和一个应该可以滑入和滑出的 View 。 p>

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)")
}

slideIn() 动画很好,就像它应该的那样。问题是我不知道如何制作 slideOut() 动画。如果我只是像上面那样停用 NSLayoutConstraint,那么什么也不会发生。相反,如果我尝试:

self.container.bottomAnchor
.constraintEqualToAnchor(self.child.topAnchor).active = true

然后会出现无法同时满足约束的警告,并且视觉上什么也没有发生。此外,每当我激活 NSLayoutConstraint 时,约束的数量 (print(container.constraints.count)) 都会增加,这不是一件好事。

所以我的问题是:

  1. 在这种情况下,如何反转 slideIn() 动画?
  2. 如何在重复动画的情况下重用现有约束,以免约束数量累加?

最佳答案

constraintEqualToAnchor 方法创建一个新约束。因此,当您在滑出函数中调用 self.container.bottomAnchor.constraintEqualToAnchor(self.child.bottomAnchor) 时,您没有使用在 slideIn 方法。

要实现所需的滑出动画,您必须保留对先前约束的引用。我不确定在约束上设置 .active 属性会在滑出函数中产生什么影响,因为我不知道您的 View 层次结构是如何设置的。但是重用约束的一种方法是将其作为 var 属性保存在您的 VC 中:

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)")
}

来自 Apple 文档:

Activating or deactivating the constraint calls addConstraint: and removeConstraint: on the view that is the closest common ancestor of the items managed by this constraint.

所以您看到约束数量增加的原因是因为您不断创建新约束并通过将 active 设置为 true 来添加它们。

关于ios - 添加、重用和删除 NSLayoutAnchors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36971883/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com