我尝试了许多不同的方法来创建具有自定义NSTableCellView的NSTableview,但我无法使其工作。问题是,我怎么能做到这一点?如何使用自定义视单元格创建NSTableview
这里是我试过的最后一件事:
而且全码::
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { var cellIdentifier: String = "" if tableColumn == tableView.tableColumns[0] { cellIdentifier = "CellID" if let cell = tableView.makeViewWithIdentifier(cellIdentifier, owner: self) as? MyTableCellView { cell.identifier = cellIdentifier // array is an array that contains NSView with layers with different colors cell.myView = array[row] return cell } } return nil }
添加标签后类的ViewController:NSViewController,NSTableViewDelegate,NSTableViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
tableview.setDelegate(self)
tableview.setDataSource(self)
let view = NSView(frame: NSRect(x: 0, y: 0, width: 200, height: 200))
view.layer?.backgroundColor = NSColor.blueColor().CGColor
array.append(view)
let view2 = NSView(frame: NSRect(x: 0, y: 0, width: 200, height: 200))
view2.layer?.backgroundColor = NSColor.greenColor().CGColor
array.append(view2)
array2label.append("bu")
array2label.append("buu")
tableview.reloadData()
// Do any additional setup after loading the view.
}
override func viewWillAppear() {
//tableview.reloadData()
laView.layer?.backgroundColor = NSColor.greenColor().CGColor
}
@IBOutlet weak var laView: NSView!
@IBOutlet weak var tableview: NSTableView!
var array = [NSView]()
var array2label = [String]()// = ["bu","buu"]
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
if (tableView.identifier == "Taula") {
return array.count
//return taulaGrafics.count
} else {
return 0
}
}
@IBOutlet weak var viewDeProva: NSView!
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
print ("Preparem la TableView")
var cellIdentifier: String = ""
if tableColumn == tableView.tableColumns[0] {
cellIdentifier = "CellID"
if let cell = tableView.makeViewWithIdentifier(cellIdentifier, owner: self) as? MyTableCellView {
print ("aqui")
print(array)
print(array2label)
cell.identifier = cellIdentifier
cell.myView = array[row]
cell.label.stringValue = array2label[row]
return cell
}
}
return nil
}
@IBAction func afegir(sender: NSButton) {
let view = NSView(frame: NSRect(x: 0, y: 0, width: 200, height: 200))
view.layer?.backgroundColor = NSColor.yellowColor().CGColor
array.append(view)
array2label.append("buLabel")
tableview.reloadData()
}
@IBAction func treure(sender: NSButton) {
array.removeLast()
tableview.reloadData()
}
}
if let cell = tableView.makeViewWithIdentifier(cellIdentifier, owner: self) as? MyTableCellView {
print ("aqui")
print(array)
print(array2label)
cell.identifier = cellIdentifier
cell.myView = array[row]
cell.myView.wantsLayer = true
cell.label.stringValue = array2label[row]
return cell
}
你有没有加入您的自定义单元格故事板中的tableView?你有没有设置标识符? – mangerlahn
@Max是的,我确实在问题 –
上看到新图像由于cellView除了myView以外什么都不做,所以错误可能在那里。要测试它,只需在cellView中添加一个标签或按钮,以检查它是否已加载。 – mangerlahn