我已经设置了一个带有嵌入式 NSTableView 的 NSView。
我已尝试为 NSTableViewCell 设置一个操作,以便在对 TableView 单元格进行更改时运行:
import Cocoa
class MyView: NSView
{
override func drawRect(dirtyRect: NSRect)
{
super.drawRect(dirtyRect)
}
@IBAction func valEntered2(sender: AnyObject)
{
Swift.print("valueEntered2")
}
}
虽然这种方法以前在 Storyboard上使用 NSViewController 时效果很好,但当我编译这段代码时它会发出警告:
“ TableView 单元格”发送的操作“valEntered2:”连接到“ View ”,这是一个无效目标(基于 TableView 的 View 内的对象它们仅连接到 TableView 的委托(delegate)。)
所以它似乎不喜欢 NSView 中的操作,所以我将 NSTableView 子类化,这样我就可以将它移到那里:
class MyTable: NSTableView, NSTableViewDataSource, NSTableViewDelegate
{
let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
override init(frame frameRect: NSRect)
{
super.init(frame: frameRect)
}
required init?(coder: NSCoder)
{
super.init(coder: coder)
self.setDataSource(self)
self.setDelegate(self)
}
override func drawRect(dirtyRect: NSRect)
{
super.drawRect(dirtyRect)
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int
{
return 5
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView?
{
let cell: NSTableCellView = tableView.makeViewWithIdentifier(tableColumn!.identifier, owner: self) as! NSTableCellView
cell.textField!.stringValue = "Hello World"
return cell
}
}
我已在 View 中设置表以使用此类:
我原以为这是此 NSTableView 的委托(delegate),并且能够将 TableViewCell 的操作添加到 MyTable,但它拒绝创建操作。
我错过了哪些步骤?
最佳答案
首先,您必须在 tableView 单元格中添加一个委托(delegate),例如
import Cocoa
protocol cellAction {
func CellAction()
}
class MyView: NSView
{
var delegate:cellAction!
override func drawRect(dirtyRect: NSRect)
{
super.drawRect(dirtyRect)
}
@IBAction func valEntered2(sender: AnyObject)
{
delegate.CellAction()
Swift.print("valueEntered2")
}
}
than after that you have to add delegate to the table view
class MyTable: NSTableView, NSTableViewDataSource, NSTableViewDelegate,cellAction
{
let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
override init(frame frameRect: NSRect)
{
super.init(frame: frameRect)
}
required init?(coder: NSCoder)
{
super.init(coder: coder)
self.setDataSource(self)
self.setDelegate(self)
}
override func drawRect(dirtyRect: NSRect)
{
super.drawRect(dirtyRect)
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int
{
return 5
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView?
{
let cell: NSTableCellView = tableView.makeViewWithIdentifier(tableColumn!.identifier, owner: self) as! NSTableCellView
cell.textField!.stringValue = "Hello World"
cell.delegate = self
return cell
}
}
in that class you have to call a method in delegate
func CellAction(){
//here you get the call back
}
关于swift - 操作系统 : Objects inside view based table views may only be connected to to the table view's delegate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37161511/