我正在用 Swift 学习 Cocoa。我创建了一个带有视图的NSTableView。
简单表视图
我还将复选框操作连接到视图控制器。但是当我单击复选框时,它打印了 -1 而不是行索引。我必须先选择该行,然后单击复选框以获取正确的索引号。无论如何都可以获取每行上每个复选框或按钮的行索引吗?这是我的代码:
进口可可
let data: [String] = ["Apple", "Microsoft", "IBM", "Tesla", "SpaceX",
"Boeing" , "Nasa"]
class ViewController: NSViewController, NSTableViewDelegate,
NSTableViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
self.table.delegate = self
self.table.dataSource = self
self.table.reloadData()
// Do any additional setup after loading the view.
}
@IBOutlet weak var table: NSTableView!
@IBAction func CheckClicked(_ sender: Any) {
print(self.table.selectedRow)
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func numberOfRows(in tableView: NSTableView) -> Int {
return data.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn:
NSTableColumn?, row: Int) -> NSView? {
if (tableColumn?.identifier)!.rawValue == "NameColumn"
{
if let cell = tableView.makeView(withIdentifier:
NSUserInterfaceItemIdentifier(rawValue: "NameColumn"), owner: self)
as? NSTableCellView
{
cell.textField?.stringValue = data[row]
return cell
}
}
else if (tableColumn?.identifier)!.rawValue == "CheckColumn"
{
if let cell = tableView.makeView(withIdentifier:
NSUserInterfaceItemIdentifier(rawValue: "CheckColumn"), owner: self)
as? NSButton
{
return cell
}
}
return nil
}
func tableViewSelectionDidChange(_ notification: Notification) {
print(self.table.selectedRow)
}
}
这就是您要查找的内容,但更好的实现是将该操作与 NSTableCellView 子类一起使用。
@IBAction func CheckClicked(_ sender: NSButton) {
// print(self.table.selectedRow)
let row = table.row(for: sender)
print("Button row (row)")
}
我只能创建一个基于NSButton的子类。
class myCustomView: NSButton{
@IBOutlet weak var CheckButton: NSButtonCell!
}
虽然我无法更改这些按钮单元格的标题。
if (tableColumn?.identifier)!.rawValue == "CheckColumn"
{
if let cell = tableView.makeView(withIdentifier:
NSUserInterfaceItemIdentifier(rawValue: "CheckColumn"), owner: self)
as? myCustomView
{
cell.CheckButton.title = data[row]
return cell
}
}
我不知道为什么Xcode不允许我创建一个基于NSTableCellView的子类。