【问题标题】:NSButton object in NSViewController not workNSViewController 中的 NSButton 对象不起作用
【发布时间】:2018-01-15 07:45:21
【问题描述】:

我正在学习写一个没有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
    }
}

我单击按钮 1,控制台输出“按钮 1”,但按钮 2 不起作用。任何想法为什么? 我在网上找了很久。但是没有用。关于如何实现这一目标的任何想法?

【问题讨论】:

  • 视图控制器是否在init末尾释放?
  • 另外,override func loadView() 在某些时候会调用super.loadView() 吗?脚注:这种事情最好覆盖viewDidLoad()

标签: swift macos cocoa appkit


【解决方案1】:

我在同一条船上,但我想我明白了。把你的

let viewController = ViewControllerTest()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多