[英]Swift: Can't center UIView in Superview with NSLayoutConstraint
[英]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 的中心相同。 但是 .neterYAnchor 不一样。
我使用 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
您也可以使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.