Hi,

I've used this function to easily add/update constraints on my views for iOS apps using AutoLayout!

Here is the function (it's a class function so you can call it anywhere in the app without needing an instance of it's class).

class func adjustOrAddConstraintFrom(view:UIView, type attributeType:NSLayoutAttribute, withConstant newConstant:CGFloat, toThisView thisView:UIView? = nil, type thisAttributeType:NSLayoutAttribute = NSLayoutAttribute.NotAnAttribute){

    var hasFoundConstraint = false

    view.constraints().map{

        (var theConstraint)->AnyObject in

        if var myConstraint = theConstraint as? NSLayoutConstraint {

            var isTargetingCorrectView = false

            if myConstraint.firstItem as? UIView == thisView || myConstraint.secondItem as? UIView == thisView {

                isTargetingCorrectView = true
            }

            if myConstraint.firstAttribute == attributeType && isTargetingCorrectView == true {

                myConstraint.constant = newConstant
                hasFoundConstraint = true

            }else if myConstraint.secondAttribute == attributeType && isTargetingCorrectView == true {

                myConstraint.constant = newConstant
                hasFoundConstraint = true
            }
        }

        return theConstraint
    }

    if hasFoundConstraint == false {

        let newConstraint = NSLayoutConstraint(item: view, attribute: attributeType, relatedBy: NSLayoutRelation.Equal, toItem: thisView, attribute: thisAttributeType, multiplier: 1.0, constant: newConstant)

        view.addConstraint(newConstraint)
    }
}

So how does this work?

There are a lot of parameters but some of them have default values so you can exclude them. It depends on the type of constraint you want to modify.

Here is an example implementation for changing the width constraint of a view:

adjustOrAddConstraintFrom(ViewIWantToAddTheConstraintTo, type:NSLayoutAttribute.Width, withConstant:TheWidthAmountInUnits)

You'll see that we didn't need to use the last 2 parameters because the constraint is only targeting itself.

Here is an example of using this method to align a view's top edge to another view's bottom edge:

adjustOrAddConstraintFrom(ViewIWantToAddTheConstraintTo, type:NSLayoutAttribute.Width, withConstant:0, toThisView:AnotherView, type:NSLayoutAttribute.Height)

Remember, this function will update an existing constraint if it already exists, this is where it really saves me time.

I hope this function helps you out!

Thanks to Yari D'areglia whose article: "Learn to love AutoLayout programmatically" really helped me!