0

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,,,

3 Answers3

0

How about:

view1.center = CGPoint(x: self.view.frame.size.width  / 2, y: self.view.frame.size.height / 2)

Another option:

view1.center = self.view.convert(self.view.center, from:self.view.superview)
grow4gaurav
  • 3,145
  • 1
  • 11
  • 12
0

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)

Teju Amirthi
  • 174
  • 6
0

If you want to center vertically without the navigation bar affecting the constraint use the safeAreaLayoutGuide centerYAnchor:

view1.centerYAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.centerYAnchor).isActive = true
Claudio
  • 5,078
  • 1
  • 22
  • 33