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

标签 swift nslayoutconstraint

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

相关文章:

ios - 是否可以将 UIView 的顶部固定到导航栏的底部?

ios - 向自定义 UIButton 添加约束不起作用

ios - 带有 2 个换行符的 NSmutablestring 使程序崩溃

swift - 在 NSViewController 子类中组织函数的替代方法?

ios - 快速更改 Storyboard

ios - 如何只保留 UITextField 的下边框?

ios - 如何添加 iOS 10 默认注释/图钉?

swift - 设置 constraint.isActive = true 时抛出错误

ios - 文件是为 arm64 构建的,它不是链接的体系结构 (x86_64)

ios - 在 View 中创建对中心标签的约束