我想为macOS创建一个带有swift 3的NSOutlineView。 因此我找到了一个youtube教程,它带给我这个好结果:
但此大纲视图的数据是静态的。 现在我想用核心数据中的数据填充大纲视图。
我知道核心数据,我知道如何从中获取数据。 但我不知道如何将它动态填充到大纲视图中。
这是我目前的代码:
ViewController.swift
import Cocoa
class ViewController: NSViewController, NSOutlineViewDataSource, NSOutlineViewDelegate {
@IBOutlet var treeController: NSTreeController!
@IBOutlet weak var outlineView: NSOutlineView!
override func viewDidLoad() {
super.viewDidLoad()
addData()
}
func addData() {
let root: [String : Any] = [ "name": "Max Mustermann", "isLeaf": false ]
let dict: NSMutableDictionary = NSMutableDictionary(dictionary: root)
dict.setObject([Test()], forKey: "children" as NSCopying)
treeController.addObject(dict)
}
func isHeader(item: AnyObject) -> Bool {
if let item = item as? NSTreeNode {
return !(item.representedObject is Test)
} else {
return !(item is Test)
}
}
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
if isHeader(item: item as AnyObject) {
return outlineView.make(withIdentifier: "HeaderCell", owner: self)
} else {
return outlineView.make(withIdentifier: "DataCell", owner: self)
}
}
}
Playlist.swift 导入Cocoa
class Playlist: NSObject {
dynamic var name: String = "New Playlist"
func isLeaf() -> Bool {
return true
}
}
我希望你能帮助我:)。
var result = [Test]()
let appdelegate = NSApplication.shared().delegate as! AppDelegate
let context = appdelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Test")
do {
result = try context.fetch(request) as! [Test]
} catch { }