I am trying to find the top constraint of the view in code. The top constraint is added in storyboard, and I don\'t want to use an IBOutlet.
Logging the value of the
Here's a one-liner extension method, based on @Igor's approach:
extension UIView{
func constraint(for layoutAttribute: NSLayoutConstraint.Attribute) -> NSLayoutConstraint? {
return superview?.constraints.first { itemMatch(constraint: $0, layoutAttribute: layoutAttribute) }
}
private func itemMatch(constraint: NSLayoutConstraint, layoutAttribute: NSLayoutConstraint.Attribute) -> Bool {
if let firstItem = constraint.firstItem as? UIView, let secondItem = constraint.secondItem as? UIView {
let firstItemMatch = firstItem == self && constraint.firstAttribute == layoutAttribute
let secondItemMatch = secondItem == self && constraint.secondAttribute == layoutAttribute
return firstItemMatch || secondItemMatch
}
return false
}
}
[ I also made the method signature style to match Swift 3...5 style e.g.:
constraint(for:)
instead of findConstraint(layoutAttribute:)
.
]