如何将视图置于超级视图的中心?迅速

问题描述

这是我的代码

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)

view1的centerXAnchor与屏幕的中心相同。 但是cneterYAnchor不一样。

我使用NavigationBar,我认为view1的centerYAnchor随NavigationBar的高度移动。

因此,如果可以使用equalTo: superview.centerYAnchor,则可以将视图居中。

您有什么好主意吗?对不起,我英语不好,

解决方法

怎么样:

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

另一个选择:

view1.center = self.view.convert(self.view.center,from:self.view.superview)
,

您可以使用以下

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

Refere here for getting nav bar height programatically


如果您的需求只是将子视图居中放置在视图控制器(具有导航栏)中那样简单

您可以像下面一样使用view1.center解决方案

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

,

如果您想垂直居中而导航栏不影响约束,请使用safeAreaLayoutGuide centerYAnchor

view1.centerYAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.centerYAnchor).isActive = true