我正在学习编写一个没有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不起作用。有什么想法吗? 我在网上搜索了很长时间。但没有用。关于如何实现这一目标有什么想法吗?
最佳答案
我也遇到过同样的情况,但我想我已经明白了。把你的
let viewController = ViewControllerTest()
在 init()
之外,现在应该可以工作了
关于swift - NSViewController 中的 NSButton 对象不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48258782/