以编程方式创建NSGridView

时间:2017-07-17 13:00:26

标签: cocoa nsview appkit

由于NSGridView在Interfacebuilder中不可用,我尝试以编程方式创建一个。 我试过这样:

 class ViewController: NSViewController { 
    override func viewDidLoad() {
        super.viewDidLoad()     

        let lb1 = NSTextField(labelWithString: "Label1")
        let lb2 = NSTextField(labelWithString: "Label2")
        let lb3 = NSTextField(labelWithString: "Label3")
        let lb4 = NSTextField(labelWithString: "Label4")
        let lb5 = NSTextField(labelWithString: "Label 5 long text ...")
        let bu = NSButton(title: "Button", target: nil, action: nil)

        let empty = NSGridCell.emptyContentView

        let gridView = NSGridView(views:
        [
        [empty, lb1],
        [empty, lb2],
        [lb3, lb4],
        [lb5],
        [bu],
        ])
    self.view.addSubview(gridView)
  }

但我只得到一个空白的窗口 - 出了什么问题?

1 个答案:

答案 0 :(得分:1)

您需要将gridView的translatesAutoresizingMaskIntoConstraints属性设置为false并添加约束

gridView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
   // Your constraints
])

或者您可以手动设置框架