获取 NSLayoutConstraint 标识符不适用于 topAnchor [英] Get NSLayoutConstraint Identifier is not working for topAnchor

查看:75
本文介绍了获取 NSLayoutConstraint 标识符不适用于 topAnchor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在运行时更改某些视图的 TopAnchor 约束.

I want to change TopAnchor Constraint of some View at runtime .

约束创建:

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

但是当我尝试获取它的参考时:

But when I try to get its reference:

    if let filteredConstraint = self.myStackView.getConstraint(withIndentifier: "topAnchor") {

//Edit here
    } 

它不会进入区块

推荐答案

问题是您在错误的视图上调用了 getConstraint.当您激活 myStackView 和其他一些视图之间的约束时:

The problem is that you are calling getConstraint on the wrong view. When you activate a constraint between myStackView and some other view:

self.myStackView.topAnchor.constraint(
    equalTo: someView.bottomAnchor , constant: 20).activate(withIdentifier: "topAnchor") 

...该约束属于myStackViewsomeView 的公共superview.所以当你说

...that constraint belongs to the common superview of myStackView and someView. So when you say

self.myStackView.getConstraint(withIndentifier: "topAnchor")

...它不在那里.您正在寻找错误的约束视图.

... it isn't there. You're looking in the wrong view for your constraint.

但是您的 getConstraint 方法(显然取自 此处)是个好主意,所以让我们更正确地(更优雅地)重写它,以便我们沿着视图层次结构向上查找约束:

But your getConstraint method (evidently taken from here) is a good idea, so let's rewrite it more correctly (and more elegantly) so that we walk up the view hierarchy looking for the constraint:

extension UIView {
    func constraint(withIdentifier id: String) -> NSLayoutConstraint? {
        return self.constraints.first { $0.identifier == id } ??
               self.superview?.constraint(withIdentifier: id)
    }
}

现在(当然要更改名称)即使您在 myStackView 上调用它,您的方法调用也将起作用.

Now (changing the name of course) your method call will work even when you call it on myStackView.

这篇关于获取 NSLayoutConstraint 标识符不适用于 topAnchor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆