gpt4 book ai didi

swift - 获取 NSLayoutConstraint 标识符不适用于 topAnchor

转载 作者:行者123 更新时间:2023-11-28 13:32:43 24 4
gpt4 key购买 nike

我想在运行时更改某些 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")

...该约束属于 myStackViewsomeView 的公共(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/

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