Search code examples
swiftmacoscocoaselectornsbutton

Getting sender on a dynamically created NSButton checkbox


I'm programmatically creating NSTableViewCells and adding and NSButton with checkbox as a subview to some of them. How can I get the sender that is triggering the selector when the checkbox is toggled? This is what I have working so far, but everything I've tried in order to get the sender has been unsuccessful.

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")
}

Solution

  • The following code works for me

    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
    }}
    

    extension 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)")
    }}