Получение отправителя на динамически создаваемом флажке NSButton - PullRequest
0 голосов
/ 13 ноября 2018

Я программно создаю NSTableViewCells и добавляю и NSButton с флажком в качестве подпредставления для некоторых из них.Как я могу получить отправителя, который запускает селектор, когда флажок установлен?Это то, над чем я работаю до сих пор, но все, что я пытался получить отправителя, оказалось неудачным.

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

Ответы [ 2 ]

0 голосов
/ 14 ноября 2018

Следующий код работает для меня

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 (в 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)")
}}
0 голосов
/ 13 ноября 2018
  1. Установите target на self

    let checkbox = NSButton(checkboxWithTitle: text, target: self, action: #selector(selector))
    
  2. Используйте синтаксис, передавая один параметр

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