[英]How to center a view on the x axis using autolayout in Swift on MacOS?
Hi I'm just wanting to have a childView
centered on the x axis of a NSViewController
view
using auto layout.嗨,我只是想有一个childView
中心在x轴NSViewController
view
使用自动布局。 I'm doing the following:我正在做以下事情:
override func viewWillAppear()
{
super.viewWillAppear()
let childView = PagesView.init(frame: CGRect(x: 0, y: 0, width:100, height: 100))
childView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(childView)
childView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
}
The childView
doesn't even appear on the screen. childView
甚至不会出现在屏幕上。 When I remove the last line, then it gets positioned at 0,0.当我删除最后一行时,它会被定位在 0,0。 So something about that last line is causing it go haywire and I'm not sure why?所以关于最后一行的某些事情导致它变得混乱,我不知道为什么? I've used this exact same logic on iOS and it has worked fine.我在 iOS 上使用了完全相同的逻辑,并且运行良好。
All views should have constraints to define its location and size.所有视图都应该有约束来定义其位置和大小。
// This would create dimension constraints if your class cannot already infer them
childView.widthAnchor.constraint(equalToConstant: 100).isActive = true
childView.heightAnchor.constraint(equalToConstant: 100).isActive = true
You also need to specify a vertical anchor constraint so the view has enough information to be displayed.您还需要指定一个垂直锚点约束,以便视图有足够的信息可以显示。
childView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.