Search code examples
iosswiftlayoutautolayoutconstraints

How to set an element center of view programmatically in iOS Swift 3?


I have a view and I want to center it horizontally and vertically in its superview.

I tried this but it's not working:

let horConstraint = NSLayoutConstraint(item: webView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0.0)
view.addConstraints([horConstraint]) 

Solution

  • I would suggest trying to use Anchors which are more convenient and easy to understand. This code centered my view:

        let someView = UIView()
        someView.backgroundColor = .red
        someView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(someView)
        NSLayoutConstraint.activate([
            someView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            someView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            someView.heightAnchor.constraint(equalToConstant: 50),
            someView.widthAnchor.constraint(equalToConstant: 50)
        ])