class 内的按钮操作选择器

Button action selector inside class

我最近开始在 Swift 中进行开发(通常是嵌入式 C 开发人员)。

我想以编程方式创建一些按钮(后来不止一个)并更改其标签(仅供练习)。 为此,我创建了一个按钮 class,其中包含按钮初始化和回调函数。我的问题是 #selector 似乎没有像我预期的那样指向按钮 class 的实例,所以单击按钮什么也没做。你能告诉我我做错了什么吗?

@objc class buttontest : NSObject{
    let button = NSButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
    @objc func printSomething() {
        print("Hello")
        self.button.title="TEST13"
      }
    func buttoninit() -> NSButton{
        self.button.title="Test"
        self.button.bezelStyle=NSButton.BezelStyle.rounded
        self.button.target=self;
        //button.action = Selector(ViewController.printSomething)
        self.button.action = #selector(self.printSomething)
        return self.button
    }
}
class ViewController: NSViewController {


    private lazy var redBox = NSView(frame: NSRect(x: 0, y: 0, width: 100, height: 100))
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(redBox)
        redBox.wantsLayer = true
        redBox.layer?.backgroundColor = NSColor.red.cgColor
        
        //button.init("Test12",self,Selector(printSomething())
        let button = buttontest()
        self.view.addSubview(button.buttoninit())
        //self.view.addSubview(buttontest().buttoninit())
        // Do any additional setup after loading the view.
    }
    override func loadView() {
    self.view = NSView(frame: NSRect(x: 0, y: 0, width: NSScreen.main?.frame.width ?? 100, height: NSScreen.main?.frame.height ?? 100))
    }
    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }


}

OK版本:

@objc class buttontest : NSObject{
    let button = NSButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
    @objc func printSomething() {
        print("Hello")
        self.button.title="TEST13"
      }
    func buttoninit() -> NSButton{
        self.button.title="Test"
        self.button.bezelStyle=NSButton.BezelStyle.rounded
        self.button.target=buttonX
        self.button.action = #selector(buttontest.printSomething)
        return self.button
    }
}

let buttonX = buttontest()

class ViewController: NSViewController {

    private lazy var redBox = NSView(frame: NSRect(x: 0, y: 0, width: 100, height: 100))
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(redBox)
        redBox.wantsLayer = true
        redBox.layer?.backgroundColor = NSColor.red.cgColor
        self.view.addSubview(buttonX.buttoninit())
    }

}