簡體   English   中英

如何將視圖置於父視圖的中心? 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 的中心相同。 但是 .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

請參閱此處以編程方式獲取導航欄高度


如果您的要求就像將子視圖置於視圖 controller(具有導航欄)中一樣簡單

您也可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM