视图不加载translatesAutoresizingMaskIntoConstraints = false

时间:2018-06-20 19:04:13

标签: cocoa

这是我在NSViewController中的代码,用于加载子视图并添加约束。由于行“ view.translatesAutoresizingMaskIntoConstraints = false”,该视图无法加载,我找不到原因。

let weddingDataVC = logic.storyboardMain.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "WeddingDataVC")) as! WeddingDataVC
let myView = weddingDataVC.view
self.addChildViewController(weddingDataVC)

self.view.addSubview(myView)

myView.translatesAutoresizingMaskIntoConstraints = false
let xConstraint = NSLayoutConstraint(item: myView, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([xConstraint])

1 个答案:

答案 0 :(得分:0)

您已经失去了垂直轴的布局约束。

let yConstraint = NSLayoutConstraint(item: myView, attribute: .centerY, relatedBy: .equal, toItem: self.view, attribute: .centerY, multiplier: 1, constant: 0)
NSLayoutConstraint.activate([yConstraint])

没有足够的约束来完全定义大小和原点,然后引发异常。

添加子视图时,它将自动添加缺少的约束。如果不需要,则应自己添加所有约束。

There is more information about debugging auto layout.