iOS - Find top constraint for a view?

前端 未结 7 1413
情深已故
情深已故 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:31

    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:). ]

    0 讨论(0)
提交回复
热议问题