swift osx 使用代码给窗口上增加控件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var helloButton : NSButton = NSButton()
override func windowDidLoad() {
       
        super.windowDidLoad()

        // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
        let frame = NSRect(x: 10, y: 10, width: 200, height: 100)
        let button = NSButton(frame: frame)
        button.title = "Click me!"
       
        button.translatesAutoresizingMaskIntoConstraints = false
       
        self.window?.contentView?.addSubview(button)
       
        let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("|-[button]-|", options: .AlignAllBaseline, metrics: nil, views: ["button":button])
        NSLayoutConstraint.activateConstraints(horizontalConstraints)
       
        let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[button]-|", options: .AlignAllBaseline, metrics: nil, views: ["button":button])
        NSLayoutConstraint.activateConstraints(verticalConstraints)
       
        self.helloButton = button
       
    }

如果self.window=nil,则需要看下window的Outlets的连接是不是正确。

发表评论

电子邮件地址不会被公开。 必填项已用*标注