Software added constant not working

I am trying to add constraints programmatically to a view, which I also add programmatically to the view controller. However, it seems that the restrictions are not respected.

The view was added to the story pane for the view controller, but was not really added to the view controller view until it appears (see screenshot below).

enter image description here

I tried to add a lot of restrictions, but none of them worked so far. Now I have simplified this single restriction 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)
    }
}
+4
source share
2 answers

translatesAutoresizingMaskIntoConstraints = false , .

:
translatesAutoresizingMaskIntoConstraints

, false, , .

+17

, . . MyView xib . , :

 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
    }
}
+2

All Articles