这是我的代码
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
,则可以将视图居中。
您有什么好主意吗?对不起,我英语不好,
答案 0 :(得分:0)
怎么样:
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)
答案 1 :(得分:0)
您可以使用以下
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)
答案 2 :(得分:0)
如果您想垂直居中而导航栏不影响约束,请使用safeAreaLayoutGuide centerYAnchor
:
view1.centerYAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.centerYAnchor).isActive = true