我正在以编程方式创建NSTableViewCells并添加带有复选框的NSButton和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")
}
答案 0 :(得分:1)
将forEach
设置为target
self
使用传递一个参数的语法
let checkbox = NSButton(checkboxWithTitle: text, target: self, action: #selector(selector))
答案 1 :(得分:0)
以下代码对我有用
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 { 返回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)")
}}