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

问题描述 投票:0回答:1

嗨,我只是想使用自动布局以childView NSViewController的x轴为中心的view。我正在执行以下操作:

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上使用了完全相同的逻辑,并且运行良好。

swift macos autolayout nsview
1个回答
0
投票

所有视图都应具有约束条件以定义其位置和大小。

// 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
© www.soinside.com 2019 - 2024. All rights reserved.