NSViewController中的NSButton对象不起作用

时间:2018-01-15 07:45:22

标签: swift macos cocoa appkit

我正在学习编写没有xib的MacOS程序,我以前写过JavaScript。

ViewControllerTest.swift

class ViewControllerTest: NSViewController {
    lazy var button2 = NSButton(frame: NSMakeRect(455, 100, 50, 20))

    override func loadView() {
        ...
        button2.title = "2"
        self.view.addSubview(button2)
        button2.target = self
        button2.action = #selector(self.button2Action)

    }

    @objc public func button2Action () {
        NSLog("Button 2")
    }
}

window.swift

class Window: NSWindow {
    @objc public func button1Action () {
        NSLog("button 1")
    }

    init() {
        ...
        // Button 1
        let button1 = NSButton(frame: NSMakeRect(455, 400, 50, 20))
        button1.title = "1"
        self.contentView!.addSubview(button1)
        button1.target = self
        button1.action = #selector(self.button1Action)

        // add view
        let viewController = ViewControllerTest()
        self.contentView!.addSubview(viewController.view)
    }
}

class WindowController: NSWindowController, NSWindowDelegate {
    override func windowDidLoad() {
        super.windowDidLoad()
        self.window!.delegate = self
    }
}

window image

我点击按钮1,控制台输出“按钮1”,但按钮2不起作用。有什么想法吗? 我一直在网上搜索很长时间。但没用。有关如何实现这一目标的任何想法?

1 个答案:

答案 0 :(得分:0)

我当时在同一条船上,但我想我想通了。放

let viewController = ViewControllerTest()

init()之外,它现在应该可以正常工作