Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Introduction to Auto Layout in iOS Auto Layout in Code Equally Spaced Views

Zenek Barburka
Zenek Barburka
7,009 Points

constrains not showing up in main.storyboard

so I am trying to add constrains in code, but they don't show up in main.storyboard and obviously they don't work

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var button1: UIButton!

@IBOutlet weak var button2: UIButton!


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    addConstraints()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func addConstraints() {


    let button1topEdge = NSLayoutConstraint(item: button1, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0.0)
    let button1Center = NSLayoutConstraint(item: button1, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0.0)
    let button1Height = NSLayoutConstraint(item: button1, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 80.0, constant: 0.0)

    let button1widthConstraint = NSLayoutConstraint(item: button1, attribute: .width, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 1.0, constant: 0.0)
    let button2widthConstraint = NSLayoutConstraint(item: button2, attribute: .width, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 1.0, constant: 0.0)

    view.addConstraints([button1Height,button1Center,button1topEdge,button1widthConstraint,button2widthConstraint])
}

}