Search code examples
iosswiftautolayoutvisual-format-language

Autolayout (VFL) for View that is added with code not storyboard


If I add views from storyboard I can handle their autolayout contraints via code, but if I try this on a view that is added via code, can't handle it.

I'm calling the code below in my viewDidLoad() but doesn't works, what is the missing part?

    var testView = UIView()
    testView.backgroundColor = UIColor.greenColor()
    self.view.addSubview(testView)

    let views : [String : AnyObject] = ["testView": testView]
    var allConstraints = [NSLayoutConstraint]()

    let verticalConstraint = NSLayoutConstraint.constraintsWithVisualFormat(
        "V:|-[testView(100)]",
        options: [],
        metrics: nil,
        views: views)
    allConstraints += verticalConstraint

    let horizontalConstraint = NSLayoutConstraint.constraintsWithVisualFormat(
        "H:|-[testView(200)]",
        options: [],
        metrics: nil,
        views: views)
    allConstraints += horizontalConstraint

    NSLayoutConstraint.activateConstraints(allConstraints)

ps: also tried these lines but didn't help

    self.view.addConstraints(verticalConstraint)
    self.view.addConstraints(horizontalConstraint)

Solution

  • You need to turn off translation of autoresizing masks to constraints. By default its set to true and if you tend to forget this, it will add constraints which you did not intend to.

    You can set this to false by

    var myView = UIView()
    myView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(myView)
    

    translatesAutoresizingMaskIntoConstraints

    If this property’s value is YES, the system creates a set of constraints that duplicate the behavior specified by the view’s autoresizing mask. By default, the property is set to YES for any view you programmatically create. If you add views in Interface Builder, the system automatically sets this property to NO.