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 Constraints in Code

Can someone figure out the mistake in the below code cause it's being compiled on Xcode & causing a compiler error here

getting a "Your code couldn't be compiled" error in the quiz.

layout.swift
class MyViewController: UIViewController {

    let sampleView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(sampleView)
    }

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        sampleView.translatesAutoresizingMaskIntoConstraints = false

        // Add constraints below
        NSLayoutConstraint.activate([
            sampleView.heightAnchor.constraint(equalToConstant: 50.0),
            sampleView.widthAnchor.constraint(equalToConstant: 50.0),
            sampleView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            sampleView.centerYAnchor.constraint(equalTo: view.centerYAnchor)
            ])
    }
}

1 Answer

Okay you are doing sampleView programmatically, so you need to create it's frame, if this was storyboard that would be created for you.