Bound subview inside a superview using Autolayout programmatically

Autolayout Swift

If you need to add a subview programmatically and want to have the same width and height as the superview using AutoLayout then you have come to the right place.

Here is a nice and short explanation:

 

Add the UIView extension in your project:

extension UIView{
    func boundInside(superView: UIView){
        self.translatesAutoresizingMaskIntoConstraints = false
        superView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics:nil, views:["subview":self]))
        superView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-0-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics:nil, views:["subview":self]))
    }
}

 

Usage:

customView = UIView(frame:CGRectZero)
containerView.addSubview(customView)
customView.boundInside(containerView)

 

In this case, customView will take the bounds of the containerView.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *