2016-04-10 2 views
0

Я пробовал много разных способов создать NSTableview с пользовательским NSTableCellView, но я не мог заставить его работать. Вопрос в том, как я могу это сделать?Как создать 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 
} 

enter image description here

После добавления метки:

enter image description here

И полный код:

класс 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() 
} 
} 

enter image description here

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 
     } 
+0

Вы добавили пользовательскую ячейку tableView в раскадровке? Вы установили идентификатор? – mangerlahn

+0

@Max Да, см. Новое изображение на вопрос –

+0

Поскольку cellView ничего не делает, кроме myView, ошибка может быть там. Чтобы проверить это, добавьте метку или кнопку в cellView, чтобы проверить, загружена ли она. – mangerlahn

ответ

0

При этом изменяется вид показать цвет, который, как ожидается, будет:

class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource { 

override func viewDidLoad() { 
    super.viewDidLoad() 
    print("DidLoad") 
    tableview.setDelegate(self) 
    tableview.setDataSource(self) 
} 

override func viewWillAppear() { 
    print("WillAppear") 
    array.append(NSColor.blueColor().CGColor) 
    array2label.append("buIni") 
    tableview.reloadData() 
    laView.layer?.backgroundColor = NSColor.greenColor().CGColor 
} 

@IBOutlet weak var laView: NSView! 

@IBOutlet weak var tableview: NSTableView! 

var array = [CGColor]() 
var array2label = [String]() 

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 ("Here") 
      print(array) 
      print(array2label) 
      cell.identifier = cellIdentifier 
      cell.myView.layer?.backgroundColor = array[row] 
      cell.label.stringValue = array2label[row] 

      return cell 
     } 
    } 
    return nil 
} 

@IBAction func afegir(sender: NSButton) { 
    let color = NSColor.yellowColor().CGColor 
    array.append(color) 
    array2label.append("buLabel") 
    tableview.reloadData() 
} 
@IBAction func treure(sender: NSButton) { 
    array.removeLast() 
    array2label.removeLast() 
    tableview.reloadData() 
} 
} 

Проблема было то, что NSView внутри NSTableViewCell не может быть заменен другим видом, потому что w вы делаете то, что меняет прототип ячейки. Поэтому, если вы замените представление, NSTableViewCell не распознает этот уровень NewView (я не уверен, 100% почему). Похоже, какая-то информация делится.

Итак, как мы можем передавать информацию в ячейку tableview? Как мы можем показать слой там? Хорошо, что ответ заключается в том, что только модификация ячейки прототипа NSTableCellView, добавленной в конструктор интерфейса или его подкласс (например, мой случай, см. Ниже ячейку). Изменение его содержимого, но не NSView !, внутри функции . Смотрите в этом фрагменте кода:

if let cell = tableView.makeViewWithIdentifier(cellIdentifier, owner: self) as? MyTableCellView { 

      cell.identifier = cellIdentifier // that is to identify the cell 
      cell.myView.layer?.backgroundColor = array[row] // see that the array contains CGCOLORS not NSViews 
      // The program was not showing the colors because the 
      // view copied doesn't copy its layer, or at least 
      // doesn't show it. 
      // Even though, if you say: *******---This is incorrect: 
      cell.myView = arrayOfNSViews[row] //the program will 
      // crash when removing 2 rows, myView = nil !!!!. 
      // That is because when you remove the item of the array 
      // somehow you are removing myView too, because it make a 
      // copy or a reference to it (Not sure what exactly). 
      // Here continues the correct program: ******--- 

      cell.label.stringValue = array2label[row] 

      return cell 
} 

см также, что в случае TextField: cell.label.stringValue = array2label[row], вы измените значение строки текстового поля, а не весь NSTextfield.

Итак, ребята помнят и повторяют мои слова: «Я не собираюсь менять вид ячейки, только ее свойства». Я просто провести 4 дня, чтобы найти, что ...

Вот NStableCellView обещал:

class MyTableCellView: NSTableCellView { 

    @IBOutlet weak var myView: NSView! 

    @IBOutlet weak var label: NSTextField! 

} 

Одно изображение иерархии вида:

enter image description here

Смежные вопросы