问题
While I was editing my constraint in Xcode 7 I found identifier field in Interface Builder. What is an identifier for the constraint how do I use it? using identifier can I access constraint programmatically and change the constant? my question is why and how is that identifier is helpful?
Is there any way to access the constraint with an identifier with looping in subviews and again looping constrain subviews. I mean is there any way we can access constraint directly without a loop.
UPDATE
I Tryed this code but only width and height constrain is accessed
for subview in view.subviews {
for constraint in subview.constraints() {
if constraint.identifier == "identifier" {
return constraint
}
}
}
回答1:
HOW: The identifier is useful when debugging (e.g. constraints not matching and one of them gets broken at run time; the constraint identifiers are being shown in log so you can see which one might cause problems)
WHY: Constraint identifiers make logs easier to read, more accurate and they save you a lot of time.
Constraint editing: If you want to change constraints programmatically you will have to declare them as outlets (like a label or button), then remove them from the view (NOT the object itself) and then set them again to the view. From my knowledge you can't just "edit" the constraints programmatically.
Your code gives you only width and height because you access the view's constraints which only contains the objects' widths and heights.
回答2:
In Swift 4 it's possible:
With this extension:
extension UIView{
func constraintWith(identifier: String) -> NSLayoutConstraint?{
return self.constraints.first(where: {$0.identifier == identifier})
}
}
And you can use't this way:
if let myConstraint = myView.constraintWith(identifier: "myConstraintID"){
myConstraint.constant = 8
}
Ps: Be sure to call constraintWith(identifier: String)
on the view where the constraint was added, normally on the superView of the related view you are changing, or on itself if the constraint is for size (width/height)
来源:https://stackoverflow.com/questions/36880449/how-to-use-constraint-identifiers-in-autolayout-and-how-to-change-constrain-usin