如何在 MacOS 上使用 Swift 中的自动布局使视图在 x 轴上居中?

How to center a view on the x axis using autolayout in Swift on MacOS?

您好,我只想使用自动布局使 childViewNSViewController view 的 x 轴为中心。我正在执行以下操作:

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
}

childView 甚至没有出现在屏幕上。当我删除最后一行时,它会定位在 0,0。所以关于最后一行的某些东西导致它变得混乱,我不确定为什么?我在 iOS 上使用了完全相同的逻辑,并且运行良好。

所有视图都应该有定义其位置和大小的约束。

// 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

您还需要指定垂直锚约束,以便视图有足够的信息显示。

childView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true