【发布时间】:2019-08-01 01:40:37
【问题描述】:
我希望能够以编程方式将行添加到我的表中。 从数组中添加列标题很容易。 我有一个包含行数据的字典数组 我可以将 csv 数据导入到这个数组中。
var rowData = [[String:String]]()
我想将其转储到我的表格行中。 我错过了什么?
我已经尝试过... func numberOfRows() 和 func tableView() 但它们没有像我使用 IB 创建表时那样的效果
import Foundation
import Cocoa
class TableView:NSObject{
var tableContainer = NSScrollView.init(frame: NSRect(x:0, y: 0, width: 800, height: 200))
var tableView:NSTableView = NSTableView(frame: NSRect(x:0, y: 0, width: 800, height: 200))
func populateHeaders(){
for x in 0..<headers.count {
let column = NSTableColumn.init(identifier:NSUserInterfaceItemIdentifier(rawValue: headers[x]))
tableView.addTableColumn(column)
column.headerCell = NSTableHeaderCell(textCell: headers[x])
}
}
override init (){
super.init()
populateHeaders()
self.tableView.delegate = self
self.tableView.dataSource = self
tableView.reloadData()
tableContainer.documentView = tableView
tableContainer.hasVerticalScroller = true
}
}
extension TableView: NSTableViewDelegate, NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return csvArray.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
var result:NSTableCellView
result = tableView.makeView(withIdentifier: (tableColumn?.identifier)!, owner: self) as! NSTableCellView
result.textField?.stringValue = csvArray[row][(tableColumn?.identifier.rawValue)!]!
print("hi")
return result
}
func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
return true
}
}
没有错误,上面的代码运行。只需要一种导入行的方法。
【问题讨论】:
-
你没有使用
NSTableView的DataSource委托方法来显示表格行。 -
不确定您的意思?我试过这个
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { var result:NSTableCellView result = tableViewView.makeView(withIdentifier: (tableColumn?.identifier)!, owner: self) as! NSTableCellView result.textField?.stringValue = csvArray[row][(tableColumn?.identifier.rawValue)!]! return result }它没有填充行! -
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView?是为了什么!?基于单元格还是基于视图的表格视图单元格? -
Cell-Based 我正在使用 ViewController 上的提交按钮来更新数据,这可能是个问题...
@IBAction func submitBtn(_ sender: NSButton) { importBtnObj.isHidden = false csv.csvToList() self.view.addSubview(TableView().tableContainer) submitBtnObj.isHidden = true TableView().tableView.reloadData() }。另外,我已经更新了上面的代码......仍然无法填充行
标签: swift cocoa rows nstableview programmatically