How to program a NSOutlineView? - swift

I am having trouble creating a NSOutlineView in Xcode 8 (Swift 3). I have a plist file with some information that I would like to present in an OutlineView. The plist file looks as following (example):
Root Dictionary *(1 item)
Harry Watson Dictionary *(5 items)*
name String Harry Watson
age Int 99
birthplace String Westminster
birthdate Date 01/01/1000
hobbies Array *(2 items)*
item 0 String Tennis
item 1 String Piano
The OutlineView should look pretty similar, like follow:
name Harry Watson
age 99
birthplace Westminster
birthdate 01/01/1000
> hobbies ... (<- this should be expandable)
I already searched for NSOutlineView tutorials on Google, but everything I found was raywenderlich.com, so I read a bit but in my opinion it isn't that easy.
So I am wondering whether you could help me with the exact example above and give me some code examples, especially regarding this function:
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {}
I am not sure what to write in there.
If you have any questions, let me know.
Thanks in advance and kind regards

I find Ray Wenderlitch's tutorials vary wildly in quality. The in-jokes, the verbosity, the step-by-step handholding that assumes you know nothing about Swift is just too nauseating to me. Here's a skinny tutorial which covers the basics of populating an outline view, manually and via Cocoa Bindings.
The key to understand NSOutlineView is that you must give each row a unique identifier, be it a string, a number or an object that represents the row. NSOutlineView calls it the item. Based on this item, you will query your data model to fill the outline view with data.
This answer presents 3 approaches:
Manual: doing everything yourself in the most basic way. It's a great introduction to learn how to interact with NSOutlineView but I don't recommend this for production code.
Streamlined: the outline view is still manually populated, but the approach is more elegant. This is what I use for my own production code.
Cocoa Binding: some magicky stuff left over from the golden days of Mac OS X. While very convenient, it's not the way of the future. Consider this an advanced topic
1. Populate the outline view manually
Interface Builder Setup
We will use a very simple NSOutlineView with just two columns: Key and Value.
Select the first column and change its identifier to keyColumn. Then select the second column and change its identifier to valueColumn:
Set the identifier for the cell to outlineViewCell. You only need to do it once.
Code
Copy and paste the following to your ViewController.swift:
// Data model
struct Person {
var name: String
var age: Int
var birthPlace: String
var birthDate: Date
var hobbies: [String]
}
class ViewController: NSViewController {
#IBOutlet weak var outlineView: NSOutlineView!
// I assume you know how load it from a plist so I will skip
// that code and use a constant for simplicity
let person = Person(name: "Harry Watson", age: 99, birthPlace: "Westminster",
birthDate: DateComponents(calendar: .current, year: 1985, month: 1, day: 1).date!,
hobbies: ["Tennis", "Piano"])
let keys = ["name", "age", "birthPlace", "birthDate", "hobbies"]
override func viewDidLoad() {
super.viewDidLoad()
outlineView.dataSource = self
outlineView.delegate = self
}
}
extension ViewController: NSOutlineViewDataSource, NSOutlineViewDelegate {
// You must give each row a unique identifier, referred to as `item` by the outline view
// * For top-level rows, we use the values in the `keys` array
// * For the hobbies sub-rows, we label them as ("hobbies", 0), ("hobbies", 1), ...
// The integer is the index in the hobbies array
//
// item == nil means it's the "root" row of the outline view, which is not visible
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
if item == nil {
return keys[index]
} else if let item = item as? String, item == "hobbies" {
return ("hobbies", index)
} else {
return 0
}
}
// Tell how many children each row has:
// * The root row has 5 children: name, age, birthPlace, birthDate, hobbies
// * The hobbies row has how ever many hobbies there are
// * The other rows have no children
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if item == nil {
return keys.count
} else if let item = item as? String, item == "hobbies" {
return person.hobbies.count
} else {
return 0
}
}
// Tell whether the row is expandable. The only expandable row is the Hobbies row
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
if let item = item as? String, item == "hobbies" {
return true
} else {
return false
}
}
// Set the text for each row
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
guard let columnIdentifier = tableColumn?.identifier.rawValue else {
return nil
}
var text = ""
// Recall that `item` is the row identiffier
switch (columnIdentifier, item) {
case ("keyColumn", let item as String):
switch item {
case "name":
text = "Name"
case "age":
text = "Age"
case "birthPlace":
text = "Birth Place"
case "birthDate":
text = "Birth Date"
case "hobbies":
text = "Hobbies"
default:
break
}
case ("keyColumn", _):
// Remember that we identified the hobby sub-rows differently
if let (key, index) = item as? (String, Int), key == "hobbies" {
text = person.hobbies[index]
}
case ("valueColumn", let item as String):
switch item {
case "name":
text = person.name
case "age":
text = "\(person.age)"
case "birthPlace":
text = person.birthPlace
case "birthDate":
text = "\(person.birthDate)"
default:
break
}
default:
text = ""
}
let cellIdentifier = NSUserInterfaceItemIdentifier("outlineViewCell")
let cell = outlineView.makeView(withIdentifier: cellIdentifier, owner: self) as! NSTableCellView
cell.textField!.stringValue = text
return cell
}
}
Result
2. A more streamlined approach
Set up your Storyboard as in #1. Then copy and paste the following code to your View Controller:
import Cocoa
/// The data Model
struct Person {
var name: String
var age: Int
var birthPlace: String
var birthDate: Date
var hobbies: [String]
}
/// Representation of a row in the outline view
struct OutlineViewRow {
var key: String
var value: Any?
var children = [OutlineViewRow]()
static func rowsFrom( person: Person) -> [OutlineViewRow] {
let hobbiesChildren = person.hobbies.map { OutlineViewRow(key: $0) }
return [
OutlineViewRow(key: "Age", value: person.age),
OutlineViewRow(key: "Birth Place", value: person.birthPlace),
OutlineViewRow(key: "Birth Date", value: person.birthDate),
OutlineViewRow(key: "Hobbies", children: hobbiesChildren)
]
}
}
/// A listing of all available columns in the outline view.
///
/// Since repeating string literals is error prone, we define them in a single location here.
/// The literals must match the column identifiers in the Story Board
enum OutlineViewColumn: String {
case key = "keyColumn"
case value = "valueColumn"
init?(tableColumn: NSTableColumn) {
self.init(rawValue: tableColumn.identifier.rawValue)
}
}
class ViewController: NSViewController {
#IBOutlet weak var outlineView: NSOutlineView!
let person = Person(name: "Harry Watson", age: 99, birthPlace: "Westminster",
birthDate: DateComponents(calendar: .current, year: 1985, month: 1, day: 1).date!,
hobbies: ["Tennis", "Piano"])
var rows = [OutlineViewRow]()
override func viewDidLoad() {
super.viewDidLoad()
self.rows = OutlineViewRow.rowsFrom(person: self.person)
outlineView.dataSource = self
outlineView.delegate = self
}
}
extension ViewController: NSOutlineViewDataSource, NSOutlineViewDelegate {
/// Return the item representing each row
/// If item == nil, it is the root of the outline view and is invisible
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
switch item {
case nil:
return self.rows[index]
case let row as OutlineViewRow:
return row.children[index]
default:
return NSNull()
}
}
/// Return the number of children for each row
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
switch item {
case nil:
return self.rows.count
case let row as OutlineViewRow:
return row.children.count
default:
return 0
}
}
/// Determine if the row is expandable
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
switch item {
case let row as OutlineViewRow:
return !row.children.isEmpty
default:
return false
}
}
/// Return content of the cell
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
guard let row = item as? OutlineViewRow,
let column = OutlineViewColumn(tableColumn: tableColumn!)
else {
fatalError("Invalid row and column combination")
}
let text: String
switch column {
case .key:
text = row.key
case .value:
text = row.value == nil ? "" : "\(row.value!)"
}
let identifier = NSUserInterfaceItemIdentifier("outlineViewCell")
let view = outlineView.makeView(withIdentifier: identifier, owner: self) as! NSTableCellView
view.textField?.stringValue = text
return view
}
}
3. Using Cocoa Bindings
Another way to populate the outline view is using Cocoa Bindings, which can significantly reduce the amount of code you need to write. However, consider Cocoa Bindings an advanced topic. When it works, it's like magic, but when it doesn't, it can be very hard to fix. Cocoa Bindings are not available on iOS.
Code
For this example, let's up the ante by having the NSOutlineView showing details of multiple persons.
// Data Model
struct Person {
var name: String
var age: Int
var birthPlace: String
var birthDate: Date
var hobbies: [String]
}
// A wrapper object that represents a row in the Outline View
// Since Cocoa Binding relies on the Objective-C runtime, we need to mark this
// class with #objcMembers for dynamic dispatch
#objcMembers class OutlineViewRow: NSObject {
var key: String // content of the Key column
var value: Any? // content of the Value column
var children: [OutlineViewRow] // set to an empty array if the row has no children
init(key: String, value: Any?, children: [OutlineViewRow]) {
self.key = key
self.value = value
self.children = children
}
convenience init(person: Person) {
let hobbies = person.hobbies.map { OutlineViewRow(key: $0, value: nil, children: []) }
let children = [
OutlineViewRow(key: "Age", value: person.age, children: []),
OutlineViewRow(key: "Birth Place", value: person.birthPlace, children: []),
OutlineViewRow(key: "Birth Date", value: person.birthDate, children: []),
OutlineViewRow(key: "Hobbies", value: nil, children: hobbies)
]
self.init(key: person.name, value: nil, children: children)
}
}
class ViewController: NSViewController {
let people = [
Person(name: "Harry Watson", age: 99, birthPlace: "Westminster",
birthDate: DateComponents(calendar: .current, year: 1985, month: 1, day: 1).date!,
hobbies: ["Tennis", "Piano"]),
Person(name: "Shelock Holmes", age: 164, birthPlace: "London",
birthDate: DateComponents(calendar: .current, year: 1854, month: 1, day: 1).date!,
hobbies: ["Violin", "Chemistry"])
]
#objc lazy var rows = people.map { OutlineViewRow(person: $0) }
override func viewDidLoad() {
super.viewDidLoad()
}
}
Interface Builder setup
In your storyboard:
Add a Tree Controller from the Object Library
Select the Tree Controller and open the Attributes Inspector (Cmd + Opt + 4). Set its Children key path to children.
Open the Bindings inspector (Cmd + Opt + 7) and set up bindings for the IB objects as follow.
| IB Object | Property | Bind To | Controller Key | Model Key Path |
|-----------------|--------------------|-----------------|-----------------|-------------------|
| Tree Controller | Controller Content | View Controller | | self.rows |
| Outline View | Content | Tree Controller | arrangedObjects | |
| Table View Cell | Value | Table Cell View | | objectValue.key |
| (Key column) | | | | |
| Table View Cell | Value | Table Cell View | | objectValue.value |
| (Value column) | | | | |
(don't confuse Table View Cell with Table Cell View. Terrible naming, I know)
Result
You can use a DateFormatter for nicer date output in both approaches but that's not essential for this question.

A clear example and perfect as a start for working with a NSOutlineView.
As I work with a later Swift version, I had to change
switch (columnIdentifier, item)
to
switch (columnIdentifier.rawValue, item).
Interface Builder also did the correct adjustments for setting
let cell = outlineView.make(withIdentifier: "outlineViewCell", owner: self) as! NSTableCellView
to
let cell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "outlineViewCell"), owner: self) as! NSTableCellView

Related

App Crashes Due to Binding to Table Cell View

So I've created an NSOutlineView to display the file & directory list in a hierarchical way. I'm building a BitTorrent client (stating so the class names make sense).
As you can see, this is pretty much how the outline view looks:
The problem is associated with the Name column. In the name column, for each row, I have a checkbox and a text field side by side. This will help you get a clearer idea:
Now, I use bindings to get the value for each textfield. However, since there are 2 views (checkbox and textfield) that needs to bound to the same NSTableCellView, I'm returning a struct, from the data source, containing 2 values: a string for the text field (which holds the file/directory name), and a boolean for enabling/disabling the checkbox.
To handle the outline view (especially its data), I've set its class to TorrentContent, which is defined as below:
import Cocoa
struct Name {
let value: String
let enabled: Bool
}
class TorrentContent: NSOutlineView, NSOutlineViewDelegate, NSOutlineViewDataSource {
var content: [TorrentContentItem]
required init?(coder: NSCoder) {
let srcDir = TorrentContentItem("src")
let mainJava = TorrentContentItem("main.java")
let mainCpp = TorrentContentItem("main.cpp")
srcDir.children.append(mainJava)
srcDir.children.append(mainCpp)
content = [srcDir]
super.init(coder: coder)
delegate = self
dataSource = self
}
func outlineView(_: NSOutlineView, isItemExpandable item: Any) -> Bool {
if let _item = item as? TorrentContentItem {
if _item.children.count > 0 {
return true
} else {
return false
}
} else {
return false
}
}
func outlineView(_: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if item == nil {
return content.count
} else {
if let _item = item as? TorrentContentItem {
return _item.children.count
}
}
return 0
}
func outlineView(_: NSOutlineView, child: Int, ofItem item: Any?) -> Any {
if item != nil {
if let _item = item as? TorrentContentItem {
return _item.children[child]
}
}
return content[child]
}
func outlineView(_: NSOutlineView, objectValueFor col: NSTableColumn?, byItem item: Any?) -> Any? {
if item != nil, col != nil {
if let _item = item as? TorrentContentItem {
switch col!.title {
case "Name":
return Name(value: _item.name, enabled: false)
default:
return nil
}
}
}
return nil
}
}
I've hard-coded the data so it'll be easier for you to understand what's going on.
Focusing only on the name column, here's the part of the above code which deals with that:
func outlineView(_: NSOutlineView, objectValueFor col: NSTableColumn?, byItem item: Any?) -> Any? {
if item != nil, col != nil {
if let _item = item as? TorrentContentItem {
switch col!.title {
case "Name":
return Name(value: _item.name, enabled: false)
default:
return nil
}
}
}
return nil
}
As you can see, it returns the Name struct, which contains values for both the views. I've hard-coded the enabled value to false just for testing purposes.
Now to bind that to the textfield's value property, I've done this:
My logic is that, since objectValue is an instance of the Name struct, objectValue.value should be the value of the Name struct's instance, which is a string.
I want to bind the enabled property of the checkbox in a similar way. However, none of the bindings work. They cause the app to crash. This is what XCode shows me after it crashes everytime I attempt to view the outline view during runtime:
Only got "(lldb)" in the console.
What am I doing wrong, and how do I achieve what I want? That is, setting the property values of multiple views from the data source class.
Cocoa Bindings uses Key Value Observing (KVO) and the observed object must be KVO compatible. See Using Key-Value Observing in Swift.
You can only use key-value observing with classes that inherit from NSObject.
Mark properties that you want to observe through key-value observing with both the #objc attribute and the dynamic modifier.
Solution A: Return a KVO compatble object from outlineView(_:objectValueFor:byItem:)
Solution B: Don't use Cocoa Bindings. Create a subclass of NSTableCellView and add a enabledCheckbox outlet. Set the values in outlineView(_:viewFor:item:).

Realm Array and child relationships

I am trying to make a List in relation to my realm array. I don't know if it is possible to take a hard coded realm array and give each string its own list. Currently I have my array in a table view and when a row is selected it segues to its own viewController. I am trying to get each selected row to contain its own list. Here's the code
Data Model 1
import Foundation
import RealmSwift
class DateChange: Object {
#objc dynamic var itemId : String = UUID().uuidString
override static func primaryKey() -> String? {
return "itemId"
}
let dates = List<String>()
let selection = List<Home>()
convenience init(tag: String) {
self.init()
}
}
Data Model 2
class Home: Object {
#objc dynamic var itemId : String = UUID().uuidString
override static func primaryKey() -> String? {
return "itemId"
}
var parentCategory = LinkingObjects(fromType: Home.self, property: "selection")
View Controller 1
class WeekOfViewController: NSViewController {
let post = DateChange(tag: "")
post.dates.append("December 30th - January 5th")
post.dates.append("January 13th - January 19th")
}
func numberOfRows(in tableView: NSTableView) -> Int {
return 2
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell = tableView.makeView(withIdentifier:
NSUserInterfaceItemIdentifier(rawValue: "dateCell") , owner: self) as! NSTableCellView?
cell?.textField?.stringValue = post.dates[row]
return cell
}
func tableViewSelectionDidChange(_ notification: Notification) {
self.performSegue(withIdentifier: "selectedDate", sender: self)
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
// Unwrap the segue's identifier.
guard let identifier = segue.identifier else { return }
// Make sure this is the segue we care about.
if identifier == "selectedDate" {
let secondVC = segue.destinationController as! ViewController2
// Figure out which row was selected.
if let selectedRow = dateTableView?.selectedRow {
secondVC.selectedDate = post.dates[selectedRow]
}
View Controller 2
class ViewController2: NSViewController {
#IBAction func saveData(_ sender: NSButton) {
if let appendDate = selectedDate {
do {
try realm?.write {
let homeData = Home()
homeData.done = false
appendDate.dates.append()
}
} catch {
print("There was an error saving")
}
}
}
Yes. You can make multiple dimensional arrays.
Example:
1. Year object has a list of months
2. Month object has a list of days
3. Day object has a list of hours
4. etc, etc
When you app launches, you create a loop which initializes a Year, then initializes lots of months and appends them into the Year.Month_Array. Do the same for days_array in each month.
To save in Realm, call:
try! realm.write {
realm.add(Year)
}
Now you can read out you multi-level Realm object anytime you wish.
If my answer isn't clear, please let me know
The exact use case is a bit unclear but it seems that the app is a Master->Detail configuration where the master page contains a list of dates and then when a date is tapped, it segues to a detail page with further info.
Here's an example of code to handle the objects. You know how to populate a tableView with it's delegate methods so I'm omitting that part.
Suppose we want a list of events on the master page and then the activities of each event on the detail page. Start with two managed Realm objects; the event object which has a start and end date, the event title and the activities list within that event. Then there's the activity object.
class EventClass: Object {
#objc dynamic var start_date: Date?
#objc dynamic var end_date: Date?
#objc dynamic var event_title = ""
let activities = List<ActivityClass>()
}
class ActivityClass: Object {
#objc dynamic var title = ""
}
write an event with some activities to Realm
let formatter = DateFormatter()
formatter.dateFormat = "yyyymmdd"
let e0 = EventClass()
e0.event_title = "Workshop"
e0.start_date = formatter.date(from: "20180113")
e0.end_date = formatter.date(from: "20180119")
let a0e0 = ActivityClass()
a0e0.title = "Some activity"
let a0e1 = ActivityClass()
a0e1.title = "Another activity"
let a0e2 = ActivityClass()
a0e2.title = "Activity continues"
e0.activities.append(a0e0)
e0.activities.append(a0e1)
e0.activities.append(a0e2)
// write event 0 (e0) to realm which will create the event and activities
We are assuming both the master and detail views have tableViews, so load the events into the master tableView dataSource which is a Realm results class - it behaves like an array.
class ViewController: NSViewController {
var eventResults: Results<EventClass>? = nil
and then whenever it's time to populate the dataSource:
self.eventResults = realm.objects(EventClass.self)
and then the tableView delegate methods can get each row for display. It would look something like this on the master page
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell = tableView.makeView(withIdentifier:
NSUserInterfaceItemIdentifier(rawValue: "dateCell") , owner: self) as! NSTableCellView?
//cell?.textField?.stringValue = post.dates[row]
let event = self.eventResults[row]
cell.textField?.stringValue = "Event: \(title) from: \(start) - \(end)"
return cell
}
so then the tableView would look something like this
Event: Workshop from: 2018-12-30 - 2018-01-05
Event: Workshop from: 2018-01-13 - 2018-01-19
etc
when a row is tapped, get that event object from the master tableView datasource, self.eventResults
let tappedEvent = self.eventResults[tappedRowIndex]
and then get the activity list
let activityList = tappedEvent.activities
that activityList can be passed via the segue (or 1000 other ways) to the detail viewController and it becomes the dataSource for the detail tableView. The detail page follows the same pattern except the dataSource is the activities.
Does that help?

Building an NSOutline view with Check marks

I am looking to add checkboxes to NSOutlineview using the correct Apple recommended method - however its not clear from the documentation.
How do I add the behavour to allow users whereby if I click a parent checkbox, then it will select the children, and if I unclick it - it will deselect the children of that item?
edit: I have simplified my question and added image to make it clearer ( hopefully)
My Approach:
I have been using the wonderful answer by Code Different to build an Outline view in my mac app.
https://stackoverflow.com/a/45384599/559760
- I chose to populate the NSoutLine view using a manual process instead of using CocoaBindings.
I added in a stack view including a check box which seems to be the right approach:
My solution involves creating an array to hold the selected items in the viewcontroller and then creating functions for adding and removing
var selectedItems: [Int]?
#objc func cellWasClicked(sender: NSButton) {
let newCheckBoxState = sender.state
let tag = sender.tag
switch newCheckBoxState {
case NSControl.StateValue.on:
print("adding- \(sender.tag)")
case NSControl.StateValue.off:
print("removing- \(sender.tag)")
default:
print("unhandled button state \(newCheckBoxState)")
}
I identify the checkbutton by the tag that was assigned to the checkbox
In the interest of future Googlers I will repeat things I've written in my other answer. The difference here is this has the extra requirement that a column is editable and I have refined the technique.
The key to NSOutlineView is that you must give an identifier to each row, be it a string, a number or an object that uniquely identifies the row. NSOutlineView calls this the item. Based on this item, you will query your data model to populate the outline.
In this answer we will setup an outline view with 2 columns: an editable Is Selected column and a non-editable Title column.
Interface Builder setup
Select the first column and set its identifier to isSelected
Select the second column and set its identifier to title
Select the cell in the first column and change its identifier to isSelectedCell
Select the cell in the second column and change its identifier to titleCell
Consistency is important here. The cell's identifier should be equal to its column's identifier + Cell.
The cell with a checkbox
The default NSTableCellView contains a non-editable text field. We want a check box so we have to design our own cell.
CheckboxCellView.swift
import Cocoa
/// A set of methods that `CheckboxCelView` use to communicate changes to another object
protocol CheckboxCellViewDelegate {
func checkboxCellView(_ cell: CheckboxCellView, didChangeState state: NSControl.StateValue)
}
class CheckboxCellView: NSTableCellView {
/// The checkbox button
#IBOutlet weak var checkboxButton: NSButton!
/// The item that represent the row in the outline view
/// We may potentially use this cell for multiple outline views so let's make it generic
var item: Any?
/// The delegate of the cell
var delegate: CheckboxCellViewDelegate?
override func awakeFromNib() {
checkboxButton.target = self
checkboxButton.action = #selector(self.didChangeState(_:))
}
/// Notify the delegate that the checkbox's state has changed
#objc private func didChangeState(_ sender: NSObject) {
delegate?.checkboxCellView(self, didChangeState: checkboxButton.state)
}
}
Connecting the outlet
Delete the default text field in the isSelected column
Drag in a checkbox from Object Library
Select the NSTableCellView and change its class to CheckboxCellView
Turn on the Assistant Editor and connect the outlet
The View Controller
And finally the code for the view controller:
import Cocoa
/// A class that represents a row in the outline view. Add as many properties as needed
/// for the columns in your outline view.
class OutlineViewRow {
var title: String
var isSelected: Bool
var children: [OutlineViewRow]
init(title: String, isSelected: Bool, children: [OutlineViewRow] = []) {
self.title = title
self.isSelected = isSelected
self.children = children
}
func setIsSelected(_ isSelected: Bool, recursive: Bool) {
self.isSelected = isSelected
if recursive {
self.children.forEach { $0.setIsSelected(isSelected, recursive: true) }
}
}
}
/// A enum that represents the list of columns in the outline view. Enum is preferred over
/// string literals as they are checked at compile-time. Repeating the same strings over
/// and over again are error-prone. However, you need to make the Column Identifier in
/// Interface Builder with the raw value used here.
enum OutlineViewColumn: String {
case isSelected = "isSelected"
case title = "title"
init?(_ tableColumn: NSTableColumn) {
self.init(rawValue: tableColumn.identifier.rawValue)
}
var cellIdentifier: NSUserInterfaceItemIdentifier {
return NSUserInterfaceItemIdentifier(self.rawValue + "Cell")
}
}
class ViewController: NSViewController {
#IBOutlet weak var outlineView: NSOutlineView!
/// The rows of the outline view
let rows: [OutlineViewRow] = {
var child1 = OutlineViewRow(title: "p1-child1", isSelected: true)
var child2 = OutlineViewRow(title: "p1-child2", isSelected: true)
var child3 = OutlineViewRow(title: "p1-child3", isSelected: true)
let parent1 = OutlineViewRow(title: "parent1", isSelected: true, children: [child1, child2, child3])
child1 = OutlineViewRow(title: "p2-child1", isSelected: true)
child2 = OutlineViewRow(title: "p2-child2", isSelected: true)
child3 = OutlineViewRow(title: "p2-child3", isSelected: true)
let parent2 = OutlineViewRow(title: "parent2", isSelected: true, children: [child1, child2, child3])
child1 = OutlineViewRow(title: "p3-child1", isSelected: true)
child2 = OutlineViewRow(title: "p3-child2", isSelected: true)
child3 = OutlineViewRow(title: "p3-child3", isSelected: true)
let parent3 = OutlineViewRow(title: "parent3", isSelected: true, children: [child1, child2, child3])
child3 = OutlineViewRow(title: "p4-child3", isSelected: true)
child2 = OutlineViewRow(title: "p4-child2", isSelected: true, children: [child3])
child1 = OutlineViewRow(title: "p4-child1", isSelected: true, children: [child2])
let parent4 = OutlineViewRow(title: "parent4", isSelected: true, children: [child1])
return [parent1, parent2, parent3, parent4]
}()
override func viewDidLoad() {
super.viewDidLoad()
outlineView.dataSource = self
outlineView.delegate = self
}
}
extension ViewController: NSOutlineViewDataSource, NSOutlineViewDelegate {
/// Returns how many children a row has. `item == nil` means the root row (not visible)
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
switch item {
case nil: return rows.count
case let row as OutlineViewRow: return row.children.count
default: return 0
}
}
/// Returns the object that represents the row. `NSOutlineView` calls this the `item`
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
switch item {
case nil: return rows[index]
case let row as OutlineViewRow: return row.children[index]
default: return NSNull()
}
}
/// Returns whether the row can be expanded
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
switch item {
case nil: return !rows.isEmpty
case let row as OutlineViewRow: return !row.children.isEmpty
default: return false
}
}
/// Returns the view that display the content for each cell of the outline view
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
guard let item = item as? OutlineViewRow, let column = OutlineViewColumn(tableColumn!) else { return nil }
switch column {
case .isSelected:
let cell = outlineView.makeView(withIdentifier: column.cellIdentifier, owner: self) as! CheckboxCellView
cell.checkboxButton.state = item.isSelected ? .on : .off
cell.delegate = self
cell.item = item
return cell
case .title:
let cell = outlineView.makeView(withIdentifier: column.cellIdentifier, owner: self) as! NSTableCellView
cell.textField?.stringValue = item.title
return cell
}
}
}
extension ViewController: CheckboxCellViewDelegate {
/// A delegate function where we can act on update from the checkbox in the "Is Selected" column
func checkboxCellView(_ cell: CheckboxCellView, didChangeState state: NSControl.StateValue) {
guard let item = cell.item as? OutlineViewRow else { return }
// The row and its children are selected if state == .on
item.setIsSelected(state == .on, recursive: true)
// This is more efficient than calling reload on every child since collapsed children are
// not reloaded. They will be reloaded when they become visible
outlineView.reloadItem(item, reloadChildren: true)
}
}
Result

swift outline view with two sub children

i working with swift 4 for macOS and i have a NSOutlineView:
i get the data from core data.
structure:
entity Person (relationship to entity Book)
entity Book
My Code for this result:
#IBOutlet weak var myOutlineView: NSOutlineView!
let context = (NSApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var people = [Person]()
override func viewWillAppear() {
requestPeople()
}
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
let view = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Cell"), owner: self) as? CustomCell
if let person = item as? Person {
// Show Person
} else if let book = item as? Book {
// Show Books
}
return view
}
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if let person = item as? Person {
return person.books.count
}
return people.count
}
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
if let person = item as? Person {
return person.books[index]
}
return people[index]
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
if let person = item as? Person {
return person.books.count > 0
}
return false
}
func requestPeople() {
let request = NSFetchRequest<Person>(entityName: "Person")
do {
people = try context.fetch(request)
myOutlineView.reloadData()
} catch { print(error) }
}
now my problem:
i would like create another outline view.
My Book entity looks like this (attributes):
name
creationDate
My new outlineview should get this structure:
+ Year
++ Month
+++ Bookname
but i dont know how can I realize this structure.
It is different as my first outline view.
can somebody help me?
=======
i guess that i have create arrays for year and month without duplicates.
for this i try a this function to get the data:
var year = [String]()
var month = [String]()
var books = [Book]()
func requestBooks() {
let request = NSFetchRequest<Book>(entityName: "Book")
do {
books = try context.fetch(request)
for x in 0 ...< books.count {
if !year.contains("\(Calendar.current.component(.year, from: books[x].creationDate))") {
year.append("\(Calendar.current.component(.year, from: books[x].creationDate))")
}
if !month.contains("\(Calendar.current.component(.month, from: books[x].creationDate))") {
month.append("\(Calendar.current.component(.month, from: books[x].creationDate))")
}
}
myOutlineView.reloadData()
} catch { print(error) }
}
A multi-level outline is easier to manage when your underlying data structure is hierarchical (i.e. a tree structure).
Here's an example of how you can create a "Tree" node class for your Books:
class BookNode
{
// levels and relationships, from parent to children
enum Level { case Top, Year, Month, Book }
let subLevels:[Level:Level] = [ .Top:.Year, .Year:.Month, .Month:.Book ]
var label = "" // description and unique "key"
var level = Level.Top
var children : [BookNode] = []
var book : Book! = nil // .Book level will store the actual Book
// add book to hierarchy, auto-create intermediate levels
func add(_ book:Book)
{
var subLabel = ""
switch level
{
case .Top : subLabel = String(Calendar.current.component(.year, from:book.creationDate))
case .Year : subLabel = String(Calendar.current.component(.month, from:book.creationDate))
case .Month : subLabel = book.name
case .Book : self.book = book // last level stores the book
return // and has no children
}
// Add branch (.Year, .Month) or leaf (.Book) node as needed
var subNode:BookNode! = children.first{$0.label == subLabel}
if subNode == nil
{
subNode = BookNode()
subNode.level = subLevels[level]!
subNode.label = subLabel
children.append(subNode)
}
// keep adding recursively down to .Book level
subNode.add(book)
}
}
Your data will be stored in a hierarchy of BookNodes which you can load from your fetch request
(you can pre-sort it, as I did, or leave that up to the BookNode class)
var topNode = BookNode()
func requestBooks()
{
let request = NSFetchRequest<Book>(entityName: "Book")
do {
let books = try context.fetch(request)
topNode = BookNode()
for book in books.sorted(by:{$0.creationDate < $1.creationDate})
{
topNode.add(book)
}
}
}
With this, it will be easy to respond to your outline protocols using the BookNodes as the outline items:
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView?
{
let view = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Cell"), owner: self) as? CustomCell
let node = (item as? BookNode) ?? topNode
switch node.level
{
case .Year : // show year : node.label
case .Month : // show month : node.label
case .Book : // show book name : node.label and/or node.book
default : break
}
return view
}
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int
{
let node = (item as? BookNode) ?? topNode
return node.children.count
}
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any
{
let node = (item as? BookNode) ?? topNode
return node.children[index]
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool
{
let node = (item as? BookNode) ?? topNode
return node.children.count > 0
}
If you program needs to allow adding/changing/removing individual books, the BookNode class can be used to reflect the individual changed (e.g. remove a book child or add a new one). You will then only need to call reloadData() on the outline without having to get everything back from the database.

Reload a NSWindow Xcode Swift2

I'm working on an NSOutlineView that uses NSView subclasses to generate custom cells in the outline. This I've gotten to work, BUT after the Outline sucks in the data from the model class and displays it correctly, the Outline is released(?) from memory / goes to nil and I haven't figured out a way to get it back.
Here is the MainViewController class
class MainWindowController: NSWindowController, ShareInfoDelegate, NSOutlineViewDelegate, NSOutlineViewDataSource {
override var windowNibName: String {
return "MainWindowController"
}
#IBOutlet var daOutline: NSOutlineView!
// The NSoutline I'm trying to get back to
Some stuff related to the test data (Omitted)
leading us to the NSOutlineViewDataSource stuff
//MARK: - NSOutlineViewDataSource
func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject {
if let item: AnyObject = item {
switch item {
case let work as Work:
return work.movements[index]
case let movement as Movement:
return movement.tracks[index]
default:
let track = item as! Track
return track.credits[index]
}
} else {
if allWorks.count > 0 {
return allWorks[index]
}
}
let q = "patience"
return q
}
func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool {
switch item {
case let work as Work:
return (work.movements.count > 0) ? true : false
case let movement as Movement:
return (movement.tracks.count > 0) ? true : false
case let track as Track:
return (track.credits.count > 0) ? true: false
default:
return false
}
}
func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int {
if let item: AnyObject = item {
switch item {
case let work as Work:
return work.movements.count
case let movement as Movement:
return movement.tracks.count
case let track as Track:
return track.credits.count
default:
return 0
}
} else {
return allWorks.count
}
}
func outlineView(daOutline: NSOutlineView, viewForTableColumn theColumn: NSTableColumn?, item: AnyObject) -> NSView? {
switch item {
case let worked as Work:
let cell = daOutline.makeViewWithIdentifier("newTry", owner:self) as! newTry
cell.fourthLabel.stringValue = worked.composer
cell.fourthCell.stringValue = worked.title
return cell
case let moved as Movement:
let cell2 = daOutline.makeViewWithIdentifier("SecondTry", owner:self) as! SecondTry
cell2.roman.stringValue = moved.name!
cell2.details.stringValue = moved.sections!
cell2.track.stringValue = "0"
return cell2
default:
print("probably not")
}
print("not again")
return nil
}
func outlineView(daOutline: NSOutlineView, heightOfRowByItem item: AnyObject) -> CGFloat {
switch item {
case let worked as Work:
return 40
default:
return 24
}
}
And the stuff in WindowDidLoad
override func windowDidLoad() {
super.windowDidLoad()
let nib = NSNib(nibNamed: "newTry", bundle: NSBundle.mainBundle())
daOutline.registerNib(nib!, forIdentifier: "newTry")
let nib2 = NSNib(nibNamed: "SecondTry", bundle: NSBundle.mainBundle())
daOutline.registerNib(nib2!, forIdentifier: "SecondTry")
//give Sender it's Receiver
mailItOut.delegate = receiver
allWorks.append(work1)
allWorks.append(work2)
work1.movements.append(move1)
work1.movements.append(move2)
work1.movements.append(move3)
work1.movements.append(move4)
work2.movements.append(move5)
work2.movements.append(move6)
work2.movements.append(move7)
daOutline.reloadData()
daOutline?.expandItem(work1, expandChildren: false)
daOutline?.expandItem(work2, expandChildren: false)
}
}
And Finally what the newTry NSView class looks like
class newTry: NSView {
var delegate: ShareInfoDelegate?
#IBOutlet weak var fourthCell: NSTextField!
#IBOutlet weak var fourthLabel: NSTextField!
#IBAction func cellAdd(sender: NSTextField) {
var catchIt: String = String()
catchIt = sender.stringValue
if catchIt != "" {
tryAgain = catchIt
whichField = "title"
//Trigger the sender to send message to it's Receiver
mailItOut.sendMessage()
}
}
The cellAdd Action is used to try and get user input from the text cells back into the model. To do this I (AFAIK) need to access the NSOutline (daOutline) and get which row I'm at and put the data from the sender into the appropriate part of the Model class. Which is something that I've managed to get to work in a standard (1 cell / 1 data value) outline. But in this prototype, as far as I can tell, the MainWindowController has released all of its contents and daOutline is nil (bad).
How do I get XCode to bring / reload the completed outline (or never release it) and get daOutline to a non nil state?
For those who come after there appeared to be two problems that led to the NSOutline outlet becoming nil. The first one was that in implementing the delegate protocol "shareInfoDelegate" I was creating a new instance of the MainWindowController, not the one with the data in it. This new instance did NOT have the IBOutlets connected (or much of anything useful about it).
Once I scrapped the Delegate and moved to using NSNotification to update information about the NSView textFields my NSOutline came "back".
The second, more minor, problem was that in the NSView nib file I placed and NSBox to mimic the behavior of a group row (e.g. a gray background). As a side effect the NSBox was inhibiting the normal row select behavior of the outline. Which made it very hard to determine which row was selected. When I deleted the NSBox, row selection became much more easy to determine.
in particular this Question and the answer by Chuck were helpful in sniffing this out.
Why is my NSOutlineView datasource nil?
Thanks Indeed(!)