如何"find"自己约束?

How to "find" your own constraint?

假设我有一个 UIView,

 class CleverView: UIView

在自定义class中,我想这样做:

func changeWidth() {

  let c = ... find my own layout constraint, for "width"
  c.constant = 70 * Gameinfo.ImportanceOfEnemyFactor
}

同样,我希望能够像那样"find",将约束(或者我猜,所有约束,可能不止一个)附加到四个边之一。

因此,查看所有附加到我的约束,并找到任何 width/height 个,或者确实与给定的(例如,"left")边缘相关的任何约束。

有什么想法吗?

也许值得注意


请注意,(显然)我在问如何做到这一点 dynamically/programmatically。

(是的,您可以说 "link to the constraint" 或 "use an ID" - QA 的重点是如何即时找到它们并动态工作。)

如果您不熟悉约束,请注意 .constraints 只为您提供了存储的末端 "there"。

我猜你可以使用 constraints 属性 of UIViewconstraints 基本上 returns 直接分配给 UIView 的约束数组。它无法让您获得 superview 持有的约束,例如前导、尾随、顶部或底部,但宽度和高度约束由 View 本身持有。对于superview的约束,可以循环遍历superview的约束。假设聪明的观点有这些限制:

class CleverView: UIView {

    func printSuperViewConstriantsCount() {
        var c = 0
        self.superview?.constraints.forEach({ (constraint) in
            guard constraint.secondItem is CleverView || constraint.firstItem is CleverView else {
                return
            }
            c += 1
            print(constraint.firstAttribute.toString())
        })
        print("superview constraints:\(c)")
    }

    func printSelfConstriantsCount() {
        self.constraints.forEach { (constraint) in
            return print(constraint.firstAttribute.toString())
        }
        print("self constraints:\(self.constraints.count)")
    }
}

输出:

顶部
领先
尾随
超级视图 constraints:3
身高
自我 constraints:1

基本上,您可以查看 NSLayoutConstraint class 以获取有关特定约束的信息。

要打印约束的名称,我们可以使用这个扩展

extension NSLayoutAttribute {
    func toString() -> String {
        switch self {
        case .left:
            return "left"
        case .right:
            return "right"
        case .top:
            return "top"
        case .bottom:
            return "bottom"
        case .leading:
            return "leading"
        case .trailing:
            return "trailing"
        case .width:
            return "width"
        case .height:
            return "height"
        case .centerX:
            return "centerX"
        case .centerY:
            return "centerY"
        case .lastBaseline:
            return "lastBaseline"
        case .firstBaseline:
            return "firstBaseline"
        case .leftMargin:
            return "leftMargin"
        case .rightMargin:
            return "rightMargin"
        case .topMargin:
            return "topMargin"
        case .bottomMargin:
            return "bottomMargin"
        case .leadingMargin:
            return "leadingMargin"
        case .trailingMargin:
            return "trailingMargin"
        case .centerXWithinMargins:
            return "centerXWithinMargins"
        case .centerYWithinMargins:
            return "centerYWithinMargins"
        case .notAnAttribute:
            return "notAnAttribute"
        }
    }
}

真的有两种情况:

  1. 有关视图大小或与后代视图关系的约束在自身中保存
  2. 两个视图之间的约束保存在视图的最低共同祖先中

重复。对于两个视图之间的约束。 iOS 事实上,总是将它们存储在最低的共同祖先中。 因此,始终可以通过搜索视图的所有祖先来找到视图的约束。

因此,我们需要检查视图本身及其所有父视图的约束。一种方法可能是:

extension UIView {

    // retrieves all constraints that mention the view
    func getAllConstraints() -> [NSLayoutConstraint] {

        // array will contain self and all superviews
        var views = [self]

        // get all superviews
        var view = self
        while let superview = view.superview {
            views.append(superview)
            view = superview
        }

        // transform views to constraints and filter only those
        // constraints that include the view itself
        return views.flatMap({ [=10=].constraints }).filter { constraint in
            return constraint.firstItem as? UIView == self ||
                constraint.secondItem as? UIView == self
        }
    }
}

您可以在获得有关视图的所有约束后应用各种过滤器,我想这是最困难的部分。一些例子:

extension UIView {

    // Example 1: Get all width constraints involving this view
    // We could have multiple constraints involving width, e.g.:
    // - two different width constraints with the exact same value
    // - this view's width equal to another view's width
    // - another view's height equal to this view's width (this view mentioned 2nd)
    func getWidthConstraints() -> [NSLayoutConstraint] {
        return getAllConstraints().filter( {
            ([=11=].firstAttribute == .width && [=11=].firstItem as? UIView == self) ||
            ([=11=].secondAttribute == .width && [=11=].secondItem as? UIView == self)
        } )
    }

    // Example 2: Change width constraint(s) of this view to a specific value
    // Make sure that we are looking at an equality constraint (not inequality)
    // and that the constraint is not against another view
    func changeWidth(to value: CGFloat) {

        getAllConstraints().filter( {
            [=11=].firstAttribute == .width &&
                [=11=].relation == .equal &&
                [=11=].secondAttribute == .notAnAttribute
        } ).forEach( {[=11=].constant = value })
    }

    // Example 3: Change leading constraints only where this view is
    // mentioned first. We could also filter leadingMargin, left, or leftMargin
    func changeLeading(to value: CGFloat) {
        getAllConstraints().filter( {
            [=11=].firstAttribute == .leading &&
                [=11=].firstItem as? UIView == self
        }).forEach({[=11=].constant = value})
    }
}

// 编辑:增强示例并在评论中阐明它们的解释

可能会节省一些打字时间......

根据 stakri 的赏金答案,以下是获得赏金的确切方法

“另一个视图的部分宽度”类型的所有约束

“定点宽度”类型的所有约束

“您的 x 位置”类型的所有约束

所以..

 fileprivate extension UIView {
    func widthAsPointsConstraints()->[NSLayoutConstraint] {}
    func widthAsFractionOfAnotherViewConstraints()->[NSLayoutConstraint] {}
    func xPositionConstraints()->[NSLayoutConstraint]
}

完整代码如下。当然,你也可以用同样的方法来做“高度”。

所以,像这样使用它们...

let cc = someView.widthAsFractionOfAnotherViewConstraints()
for c in cc {
   c.changeToNewConstraintWith(multiplier: 0.25)
}

let cc = someView.widthAsPointsConstraints()
for c in cc {
    c.constant = 150.0
}

此外,我在底部粘贴了一个简单的演示代码,示例输出...

这是代码。 V2 ...

fileprivate extension UIView { // experimental
    
    func allConstraints()->[NSLayoutConstraint] {
        
        var views = [self]
        var view = self
        while let superview = view.superview {
            
            views.append(superview)
            view = superview
        }
        
        return views.flatMap({ [=13=].constraints }).filter { constraint in
            return constraint.firstItem as? UIView == self ||
                constraint.secondItem as? UIView == self
        }
    }
    
     func widthAsPointsConstraints()->[NSLayoutConstraint] {

        return self.allConstraints()
         .filter({
            ( [=13=].firstItem as? UIView == self && [=13=].secondItem == nil )
         })
         .filter({
            [=13=].firstAttribute == .width && [=13=].secondAttribute == .notAnAttribute
         })
    }
    
    func widthAsFractionOfAnotherViewConstraints()->[NSLayoutConstraint] {
        
        func _bothviews(_ c: NSLayoutConstraint)->Bool {
            if c.firstItem == nil { return false }
            if c.secondItem == nil { return false }
            if !c.firstItem!.isKind(of: UIView.self) { return false }
            if !c.secondItem!.isKind(of: UIView.self) { return false }
            return true
        }
        
        func _ab(_ c: NSLayoutConstraint)->Bool {
            return _bothviews(c)
                && c.firstItem as? UIView == self
                && c.secondItem as? UIView != self
                && c.firstAttribute == .width
        }
        
        func _ba(_ c: NSLayoutConstraint)->Bool {
            return _bothviews(c)
                && c.firstItem as? UIView != self
                && c.secondItem as? UIView == self
                && c.secondAttribute == .width
        }
        
        // note that .relation could be anything: and we don't mind that
        
        return self.allConstraints()
            .filter({ _ab([=13=]) || _ba([=13=]) })
    }

     func xPositionConstraints()->[NSLayoutConstraint] {

         return self.allConstraints()
            .filter({
         return [=13=].firstAttribute == .centerX || [=13=].secondAttribute == .centerX
         })
    }
}

extension NSLayoutConstraint {
    
    // typical routine to "change" multiplier fraction...
    
    @discardableResult
    func changeToNewConstraintWith(multiplier:CGFloat) -> NSLayoutConstraint {

        //NSLayoutConstraint.deactivate([self])
        self.isActive = false
        
        let nc = NSLayoutConstraint(
            item: firstItem as Any,
            attribute: firstAttribute,
            relatedBy: relation,
            toItem: secondItem,
            attribute: secondAttribute,
            multiplier: multiplier,
            constant: constant)

        nc.priority = priority
        nc.shouldBeArchived = self.shouldBeArchived
        nc.identifier = self.identifier

        //NSLayoutConstraint.activate([nc])
        nc.isActive = true
        return nc
    }
}

只是一个示例演示...

override func viewDidAppear(_ animated: Bool) {
    
    super.viewDidAppear(animated)
    
    _teste()
    
    delay(5) {
        print("changing any 'fraction fo another view' style widths ...\n\n")
        let cc = self.animeHolder.widthAsFractionOfAnotherViewConstraints()
        for c in cc {
            c.changeToNewConstraintWith(multiplier: 0.25)
        }
        self._teste()
    }
    
    delay(10) {
        print("changing any 'points' style widths ...\n\n")
        let cc = self.animeHolder.widthAsPointsConstraints()
        for c in cc {
            c.constant = 150.0
        }
        self._teste()
    }
}

func _teste() {
    
    print("\n---- allConstraints")
    for c in animeHolder.allConstraints() {
        print("\n \(c)")
    }
    print("\n---- widthAsPointsConstraints")
    for c in animeHolder.widthAsPointsConstraints() {
        print("\n \(c)\n \(c.multiplier) \(c.constant)")
    }
    print("\n---- widthAsFractionOfAnotherViewConstraints")
    for c in animeHolder.widthAsFractionOfAnotherViewConstraints() {
        print("\n \(c)\n \(c.multiplier) \(c.constant)")
    }
    print("\n----\n")
}