Search code examples
iosswiftnslayoutconstraint

Swift: Can't center UIView in Superview with NSLayoutConstraint


i'm trying to center a view in the parent view but its not centering as expected. Here is my code an a screenshot of the result.

emptyView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(emptyView)
let centerXConstraint = NSLayoutConstraint(item: emptyView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)
let centerYConstraint = NSLayoutConstraint(item: emptyView, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0)
self.view.addConstraints([centerXConstraint])
self.view.addConstraints([centerYConstraint])

Preview


Solution

  • Here is the code,

    import UIKit
    
    class ViewController: UIViewController
    {
        @IBOutlet weak var emptyView: UIView!
    
        override func viewDidLoad()
        {
            super.viewDidLoad()
            self.emptyView.translatesAutoresizingMaskIntoConstraints = false
            let centerXConstraint = NSLayoutConstraint(item: emptyView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)
            let centerYConstraint = NSLayoutConstraint(item: emptyView, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0)
            let widthConstraint = NSLayoutConstraint(item: emptyView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100)
            let heightConstraint = NSLayoutConstraint(item: emptyView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100)
    
            self.view.addConstraints([centerXConstraint, centerYConstraint, widthConstraint, heightConstraint])
            self.view.layoutIfNeeded()
        }
    }
    

    If you are using label or button or any other view that have intrinsic size, there is no need for height and width constraints

    ViewController Interface :

    enter image description here

    Output :

    enter image description here