在动态创建的 NSButton 复选框上获取发件人

Getting sender on a dynamically created NSButton checkbox

我正在以编程方式创建 NSTableViewCells 并添加 NSButton with checkbox 作为其中一些的子视图。切换复选框时,如何获取触发选择器的发件人?这是我目前所做的工作,但我为获得发件人所做的一切尝试都没有成功。

func addCheckBox(cell: NSTableCellView){
    let checkbox = NSButton(checkboxWithTitle: text, target: Any?.self, action: #selector(selector))
    checkbox.setButtonType(NSButton.ButtonType.onOff)
    cell.addSubview(checkbox)

}

@objc func selector(){
    print("selector selected")
}
  1. target设置为self

    let checkbox = NSButton(checkboxWithTitle: text, target: self, action: #selector(selector))
    
  2. 使用传递一个参数的语法

    @objc func selector(_ sender : NSButton){
        print("selector selected", sender.state)
    }
    

下面的代码适合我

class AppDelegate: NSObject, NSApplicationDelegate {

let mainWindow: NSWindow = {
    let window = NSWindow(contentRect: NSMakeRect(300, 300, 700, 700), styleMask: .resizable, backing: .buffered, defer: false)
    window.isOpaque = true
    window.styleMask.insert(.miniaturizable)
    window.styleMask.insert(.titled)
    window.makeKeyAndOrderFront(nil)
    window.title = "My Playground"
    window.isMovableByWindowBackground = true
    return window
}()

lazy var tableView : NSTableView = {
    let tableView = NSTableView()
    let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "Sample Column"))
    tableView.addTableColumn(column)
    tableView.dataSource = self
    tableView.delegate = self
    return tableView
}()

func applicationDidFinishLaunching(_ aNotification: Notification) {

    mainWindow.contentView = tableView
    // Insert code here to initialize your application
}

func applicationWillTerminate(_ aNotification: Notification) {
    // Insert code here to tear down your application
}}

扩展 AppDelegate: NSTableViewDataSource, NSTableViewDelegate { func numberOfRows(in tableView: NSTableView) -> Int { return 10 }

func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
    let rowView = NSView()

    let button = NSButton()
    button.bezelStyle = .texturedRounded
    button.setButtonType(.switch)
    button.target = self
    button.action = #selector(selectorName(_:))
    button.title = "\(row)th view"
    button.translatesAutoresizingMaskIntoConstraints = false


    rowView.addSubview(button)
    return rowView
}

@objc func selectorName(_ sender: NSButton)
{
    print("The state of \(sender.title) is \(sender.state)")
}}