iOS - Find top constraint for a view?

前端 未结 7 1414
情深已故
情深已故 2020-12-28 16:52

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

7条回答
  •  一生所求
    2020-12-28 17:24

    Based on @Igor answer, I changed a bit itemMatch method to consider when first item or second item is not a UIView. For example when constraint a UIView top to safe area top.

    extension UIView {
        func findConstraint(layoutAttribute: NSLayoutConstraint.Attribute) -> NSLayoutConstraint? {
            if let constraints = superview?.constraints {
                for constraint in constraints where itemMatch(constraint: constraint, layoutAttribute: layoutAttribute) {
                    return constraint
                }
            }
            return nil
        }
    
        func itemMatch(constraint: NSLayoutConstraint, layoutAttribute: NSLayoutConstraint.Attribute) -> Bool {
            let firstItemMatch = constraint.firstItem as? UIView == self && constraint.firstAttribute == layoutAttribute
            let secondItemMatch = constraint.secondItem as? UIView == self && constraint.secondAttribute == layoutAttribute
            return firstItemMatch || secondItemMatch
        }
    }
    

提交回复
热议问题