Search code examples
swiftswift3

How can I center the view on the superview? swift


This is my code

let view1 = UIView()
view1.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(view1)
view1.widthAnchor.constraint(equalToConstant: 100).isActive = true
view1.heightAnchor.constraint(equalToConstant: 100).isActive = true
view1.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
view1.centerYAnchor.constraint((equalTo: self.view.centerYAnchor).isActive = true)

The centerXAnchor of view1 is the same as the center of the Screen. However cneterYAnchor is not same.

I use NavigationBar, I think centerYAnchor of view1 shift by height of the NavigationBar.

So, if equalTo: superview.centerYAnchor is possible, I can center the view.

Do you have any good ideas? I'm sorry I'm not good at English,,,


Solution

  • You can use the below

    view1.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -navBarHeight).isActive = true

    Refere here for getting nav bar height programatically


    If your requirement is as simple as centering the subview inside a view controller (which has navigation bar)

    You can use the view1.center solution as well like below

    view1.center = CGPoint(x: UIScreen.main.bounds.width/2, y: UIScreen.main.bounds.height/2)