robhasacamera robhasacamera - 1 year ago 68
Swift Question

Programmatically Added Constraint Not Working

I've been trying to add constraints programmatically to a view that I'm also adding programmatically to my view controller. However, it seems like the constraints are not being followed.

The view has been added to the story board for the view controller, but isn't actually added to the view controller's view until later on (See screenshot below).

enter image description here

I've tried adding a variety of constraints but none of them have worked so far. I've simplified it now to the single constraint below and even this will not work. What am I doing wrong?

@IBOutlet var loadingView: LoadingView!

override func viewDidLoad() {

func displayLoadingView(display: Bool) {
if display {

let widthConstraint = NSLayoutConstraint(item: loadingView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50.0)


Answer Source

set translatesAutoresizingMaskIntoConstraints = false to any view you are settings constraints programatically.

from the apple doc:

If you want to use Auto Layout to dynamically calculate the size and position of your view, you must set this property to false, and then provide a non ambiguous, nonconflicting set of constraints for the view.