Get NSLayoutConstraint Identifier is not working for topAnchor

萝らか妹 提交于 2019-12-13 03:20:29

问题


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

Constraint Created:

 self.buttonHStack.topAnchor.constraint(equalTo: cellHStack.bottomAnchor , constant: 20).activate(withIdentifier: "topAnchor")

Extension

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

Usage

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
    } 

Its not going into the block


回答1:


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

...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.

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

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



来源:https://stackoverflow.com/questions/57117191/get-nslayoutconstraint-identifier-is-not-working-for-topanchor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!