Reputation: 4462
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">
Upvotes: 4
Views: 3117
Reputation: 465
An easy way is to compare if there exists the hash code of the view in the constraint object:
[[NSString stringWithFormat:@"%@", constraint] containsString:[NSString stringWithFormat:@"%x", view.hash]]
Upvotes: 0
Reputation: 154583
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")
Upvotes: 2