我想在运行时更改某些 View 的 TopAnchor 约束。
约束创建:
self.buttonHStack.topAnchor.constraint(equalTo: cellHStack.bottomAnchor , constant: 20).activate(withIdentifier: "topAnchor")
扩展
extension UIView {
func getConstraint(withIndentifier indentifier: String) -> NSLayoutConstraint? {
return self.constraints.filter { $0.identifier == indentifier }.first
}
}
extension NSLayoutConstraint {
func activate(withIdentifier identifier: String) {
self.identifier = identifier
self.isActive = true
}
}
用法
self.myStackView.topAnchor.constraint(equalTo: someView.bottomAnchor , constant: 20).activate(withIdentifier: "topAnchor")
但是当我试图获取它的引用时:
if let filteredConstraint = self.myStackView.getConstraint(withIndentifier: "topAnchor") {
//Edit here
}
它不会进入区 block
最佳答案
问题是您在错误的 View 上调用了 getConstraint
。当您激活 myStackView
和其他 View 之间的约束时:
self.myStackView.topAnchor.constraint(
equalTo: someView.bottomAnchor , constant: 20).activate(withIdentifier: "topAnchor")
...该约束属于 myStackView
和 someView
的公共(public) superview。所以当你说
self.myStackView.getConstraint(withIndentifier: "topAnchor")
... 它不存在。您正在寻找错误的约束 View 。
但是您的 getConstraint
方法(显然取自 here )是个好主意,所以让我们更正确(更优雅)地重写它,以便我们沿着 View 层次结构向上查找约束:
extension UIView {
func constraint(withIdentifier id: String) -> NSLayoutConstraint? {
return self.constraints.first { $0.identifier == id } ??
self.superview?.constraint(withIdentifier: id)
}
}
现在(当然要更改名称)即使您在 myStackView
上调用它,您的方法调用也会起作用。
关于swift - 获取 NSLayoutConstraint 标识符不适用于 topAnchor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57117191/