简体   繁体   中英

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

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)

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM