如何将视图置于父视图的中心? swift

How can I center the view on the superview? swift

这是我的代码

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与Screen的中心相同。 但是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