Programmatically Added Constraint Not Working

前端 未结 2 1950
旧时难觅i
旧时难觅i 2021-01-12 08:23

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

相关标签:
2条回答
  • 2021-01-12 08:38

    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.

    0 讨论(0)
  • 2021-01-12 08:42

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题