Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use constraint Identifiers in autolayout and how to change constrain using identifiers? [Swift]

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?

SNAPSHOT

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
           }
        }
    }
like image 739
O-mkar Avatar asked Apr 27 '16 04:04

O-mkar


People also ask

How do I create a constraint in Autolayout?

Control-Dragging ConstraintsIf you drag more or less horizontally, you get options to set the horizontal spacing between the views, and options to vertically align the views. If you drag more or less vertically, you get options to set the vertical spacing, and options to align the views horizontally.


2 Answers

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.

like image 135
Lawrence413 Avatar answered Oct 06 '22 00:10

Lawrence413


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)

like image 30
Romulo BM Avatar answered Oct 06 '22 00:10

Romulo BM