getting NSLayoutConstraints associated view

此生再无相见时 提交于 2019-12-10 18:16:55

问题


I trying to loop through a views constraints.

I added to view1: top, trailing, leading and height constraints.

top, trailing and leading are to the main ViewControllers view.

if i loop through view1's constraints i only see the height constraint.

for constraint in view1.constraints {
    print(constraint)
}

NSLayoutConstraint:0x6180000968a0 UIView:0x7fae6b409dd0.height == 146 (active)

so i looped through its superviews constraints (the ViewControllers main view) and i got lots of constraints some of them are associated with view1.

for constraint in view1.superview?.constraints {
    print(constraint)
}

NSLayoutConstraint:0x618000096670 H:|-(0)-[UIView:0x7fae6b409dd0] (active, names: '|':UIView:0x7fae6b40a180 )

NSLayoutConstraint:0x6180000974d0 H:[UIView:0x7fae6b409dd0]-(0)-| (active, names: '|':UIView:0x7fae6b40a180 )

NSLayoutConstraint:0x618000097520 V:|-(0)-[UIView:0x7fae6b409dd0] (active, names: '|':UIView:0x7fae6b40a180 )

and i get a few more that i dont care about.

So my problem is that i want to loop through all of view1's superviews constraints and get only the ones that are associated with it.

In this example UIView:0x7fae6b409dd0 is view1.

But i cant figure out how to get that property.

Thanks


If i print out constraint.firstAnchor i get some more information but still cant get the associated view.

NSLayoutXAxisAnchor:0x608000265480 "UIView:0x7fae6b409dd0.leading">

NSLayoutXAxisAnchor:0x608000265480 "UIView:0x7fae6b409dd0.trailing">

NSLayoutXAxisAnchor:0x608000265480 "UIView:0x7fae6b409dd0.top">


回答1:


You can use the firstItem and secondItem properties of NSLayoutConstraint to get the views related to the constraint. Note that secondItem is an Optional and must be unwrapped.

Then you can use the === operator to compare if it is the same object:

let constraints = view1.superview!.constraints
var count = 0

print("superview has \(constraints.count) constraints")

for constraint in constraints {
    if constraint.firstItem === view1 {
        count += 1
        print(constraint)
    } else if let secondItem = constraint.secondItem, secondItem === view1 {
        count += 1
        print(constraint)
    }
}

print("\(count) of them relate to view1")


来源:https://stackoverflow.com/questions/41461550/getting-nslayoutconstraints-associated-view

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