Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() {
    super.viewDidLoad()
    displayLoadingView(true)
}

func displayLoadingView(display: Bool) {
    if display {
        view.addSubview(loadingView)

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

        view.addConstraint(widthConstraint)
    }
}
like image 699
robhasacamera Avatar asked Apr 16 '16 13:04

robhasacamera


2 Answers

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

from the apple doc:
translatesAutoresizingMaskIntoConstraints

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.

like image 69
HardikDG Avatar answered Dec 15 '22 02:12

HardikDG


You don't set all necessary constraints, that can be the reason. Consider following rough example. MyView interface is defined in standalone xib file. Hope it helps:

 class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let myView = loadFromNib("MyView") else {
            return
        }

        view.addSubview(myView)

        myView.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[myView]-15-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: ["myView": myView]))

        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-15-[myView]-15-|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: ["myView": myView]))
    }

    func loadFromNib(cls: String) -> UIView? {

        return  NSBundle.mainBundle().loadNibNamed(cls, owner: nil, options: nil)[0] as? UIView
    }
}
like image 40
Igor B. Avatar answered Dec 15 '22 01:12

Igor B.