NSOutlineView, how to get the selected cell - swift

I want to get the selected cell from the NSOutlineView control. I found a solution here: How can I get the selected cell from a NSOutlineView?. It says
Use the delegate. willDisplayCell: is called when a cell changes its selection state.
However when I test it, I found that my willDisplayCell: is not be called.
Here's my code, it can be run normally, but the willDisplayCell: method has never been called. Where did I make a mistake? Thanks.
class TreeNode: NSObject{
var name: String = ""
private(set) var isLeaf: Bool = false
var children: [TreeNode]?
init(name: String, isLeaf: Bool){
self.name = name
self.isLeaf = isLeaf
if !isLeaf{
children = [TreeNode]()
}
}
}
class ViewController: NSViewController {
#IBOutlet weak var sourceList: NSOutlineView!
private var data = TreeNode(name: "Root", isLeaf: false)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
for i in 0..<10{
let node = TreeNode(name: "name \(i)", isLeaf: i % 2 == 0)
data.children?.append(node)
}
}
}
extension ViewController: NSOutlineViewDataSource {
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if let item = item as? TreeNode, !item.isLeaf {
return item.children!.count
}
return 1
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
return !((item as? TreeNode)?.isLeaf ?? false)
}
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
if let item = item as? TreeNode {
if item.isLeaf{
return item
}else{
return item.children![index]
}
}
return data
}
}
extension ViewController: NSOutlineViewDelegate {
func outlineView(_ outlineView: NSOutlineView, willDisplayCell cell: Any, for tableColumn: NSTableColumn?, item: Any) {
print("called")
}
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
let cell: NSTableCellView?
if let item = item as? TreeNode{
cell = outlineView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "DataCell"), owner: self) as? NSTableCellView
cell?.textField?.stringValue = item.name
}else{
cell = nil
}
return cell
}
}

I've solved this problem myself. The following code is how to get the selected cell:
func getSelectedCell() -> NSTableCellView? {
if let view = self.sourceList.rowView(atRow: self.sourceList.selectedRow, makeIfNecessary: false) {
return view.view(atColumn: self.sourceList.selectedColumn) as? NSTableCellView
}
return nil
}
Now I can access the NSTextField control by the code getSelectedCell()?.textField.

Related

NSOutlineView unexpectedly found nil

I am trying to make a file browser in my app that opens in a side panel (with a split view controller).
The source is a URL brought by a prepareForSegue method in the previous viewController.
Each time the vc loads i have the fatal error :
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
The compiler locates the error to where i declare :
outlineView.delegate = self
outlineView.dataSource = self
I tried :
1. Undoing and redoing all my outlets connections, by code, by
storyboard
2. Reconnecting delegates and datasource by code, by storyboard
3. I thought maybe something was wrong in my datasource method and i rewrote it 5 times
4. I tried to put my setDelegatesAndDatasource method in the viewDidAppear too, thinking it was a problem of view life cycle
I can't understand what's going on.
Thanks for your help.
'''
extension ViewControllerSource : NSOutlineViewDataSource, NSOutlineViewDelegate {
func setDelegatesAndDatasources(){
outlineView.delegate = self
outlineView.dataSource = self
}
// MARK: - NSOutlineView Datasource
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if let fileSystemItem = item as? FileSystemItem {
return fileSystemItem.children.count
}
return 1
}
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
if let fileSystemItem = item as? FileSystemItem {
return fileSystemItem.children[index]
}
return rootfileSystemItem
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
if let fileSystemItem = item as? FileSystemItem {
return fileSystemItem.hasChildren()
}
return false
}
// MARK: - NSOutlineView Delegate
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
guard let colIdentifier = tableColumn?.identifier else { return nil }
if colIdentifier == NSUserInterfaceItemIdentifier(rawValue: "col1") {
let cellIdentifier = NSUserInterfaceItemIdentifier(rawValue: "cell1")
guard let cell = outlineView.makeView(withIdentifier: cellIdentifier, owner: nil) as? NSTableCellView else { return nil }
if let collection = item as? FileSystemItem {
cell.textField?.stringValue = collection.name ?? "Title not available"
cell.textField?.isEditable = false
cell.textField?.wantsLayer = true
cell.imageView?.image = collection.icon
// cell.textField?.delegate = self
} else {
cell.textField?.stringValue = "unknown item"
cell.textField?.isEditable = false
cell.textField?.wantsLayer = true
}
return cell
} else {
return nil
}
}
}
'''
And here is the main viewController file :
'''
class ViewControllerSource: NSViewController {
#IBOutlet var outlineView: NSOutlineView!
var echo:Echo? {
didSet {
echo!.checkFolderIntegrity()
rootfileSystemItem = FileSystemItem(url: echo!.url)
let window = self.view.window?.windowController as! WindowControllerEcho
window.directoryPath.url = echo!.url
}
}
let propertyKeys: [URLResourceKey] = [.localizedNameKey, .effectiveIconKey, .isDirectoryKey, .typeIdentifierKey]
var rootfileSystemItem: FileSystemItem! {
didSet {
displayItems()
outlineView.reloadData()
}
}
// MARK: - Initialization
override func viewDidLoad() {
super.viewDidLoad()
setDelegatesAndDatasources()
}
func displayItems(){
for fileSystemItem in rootfileSystemItem.children as [FileSystemItem] {
print("item : \(fileSystemItem)")
for subItem in fileSystemItem.children as [FileSystemItem] {
print("\(fileSystemItem.name) - \(subItem.name)")
}
}
}
}
extension ViewControllerSource : EchoDelegate {
func didLoad(echo: Echo) {
self.echo = echo
}
}
'''
The prepareForSegue code reveals the mistake:
You are setting echo in prepareForSegue. This causes to call the property observer didSet. However at this moment the view is not loaded yet and force unwrapping the type crashes.
The solution is to move the code in didSet into viewDidLoad and viewWillAppear and delete the property observer. Nevertheless I recommend to optional bind window
var echo : Echo!
override func viewDidLoad() {
super.viewDidLoad()
setDelegatesAndDatasources()
echo.checkFolderIntegrity()
rootfileSystemItem = FileSystemItem(url: echo.url)
}
override func viewWillAppear(_ animated : Bool) {
super.viewWillAppear(animated)
if let window = self.view.window?.windowController as? WindowControllerEcho {
window.directoryPath.url = echo.url
}
}
Setting delegate and dataSource once is sufficient. If you are using storyboard or Xib the most convenient way is to connect both in Interface Builder.

NSOutlineView drag line stuck + blue border

I'd like a correct behaviour from the blue drag bar, and no blue rect when dragging.
Do you know where is my mistake ?
(as you can see, the blue bar is stuck in top, like in this topic :
Little circle-line bar stuck at top of NSOutlineView when rearranging using drag and drop)
import Cocoa
class ViewController: NSViewController, NSOutlineViewDataSource, NSOutlineViewDelegate, NSPasteboardItemDataProvider {
#IBOutlet weak var outlineView: NSOutlineView!
let REORDER_PASTEBOARD_TYPE = "com.test.calques.item"
override func viewDidLoad() {
super.viewDidLoad()
//Register for the dropped object types we can accept.
outlineView.register(forDraggedTypes: [REORDER_PASTEBOARD_TYPE])
//Disable dragging items from our view to other applications.
outlineView.setDraggingSourceOperationMask(NSDragOperation(), forLocal: false)
//Enable dragging items within and into our view.
outlineView.setDraggingSourceOperationMask(NSDragOperation.every, forLocal: true)
outlineView.delegate = self;
outlineView.dataSource = self;
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
var items: [(String, NSColor)] = [
("Item 1", NSColor.black),
("Item 2", NSColor.red),
("Item 3", NSColor.red),
("Item 4", NSColor.red),
("Item 5", NSColor.red),
("Item 6", NSColor.red)];
//NSOutlineViewDataSource
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
return items.count;
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
return false
}
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
return items[index];
}
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
let image: NSImage = NSImage(size: NSSize(width: 17, height: 17));
let calquesItem: (String, NSColor) = item as! (String, NSColor);
let path = NSBezierPath(ovalIn: CGRect(x: 2, y: 2, width: 17 - 4, height: 17 - 4));
image.lockFocus();
calquesItem.1.setFill();
path.fill();
image.unlockFocus();
let cell = outlineView.make(withIdentifier: "DataCell", owner: nil) as! NSTableCellView;
cell.textField!.stringValue = calquesItem.0;
cell.imageView!.image = image;
return cell;
}
//Drag - NSOutlineViewDataSource
var fromIndex: Int? = nil;
func outlineView(_ outlineView: NSOutlineView, pasteboardWriterForItem item: Any) -> NSPasteboardWriting? {
let pastBoardItem: NSPasteboardItem = NSPasteboardItem();
pastBoardItem.setDataProvider(self, forTypes: [REORDER_PASTEBOARD_TYPE]);
return pastBoardItem;
}
func outlineView(_ outlineView: NSOutlineView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forItems draggedItems: [Any]) {
Swift.print("willBeginAt")
let item = draggedItems[0] as! (String, NSColor);
fromIndex = items.index(where: { (_item: (String, NSColor)) -> Bool in
return _item.0 == item.0
});
session.draggingPasteboard.setData(Data(), forType: REORDER_PASTEBOARD_TYPE)
}
func outlineView(_ outlineView: NSOutlineView, acceptDrop info: NSDraggingInfo, item: Any?, childIndex index: Int) -> Bool {
Swift.print("acceptDrop")
if(fromIndex! != index && index != -1) {
let toIndex: Int = fromIndex! < index ? index - 1 : index;
outlineView.moveItem(at: fromIndex!, inParent: nil, to: toIndex, inParent: nil);
items.insert(items.remove(at: fromIndex!), at: toIndex);
return true;
}
return false;
}
func outlineView(_ outlineView: NSOutlineView, validateDrop info: NSDraggingInfo, proposedItem item: Any?, proposedChildIndex index: Int) -> NSDragOperation {
if(item == nil) {
return NSDragOperation.generic;
}
return [];
}
func outlineView(_ outlineView: NSOutlineView, draggingSession session: NSDraggingSession, endedAt screenPoint: NSPoint, operation: NSDragOperation) {
Swift.print("Drag session ended")
fromIndex = nil;
}
//NSPasteboardItemDataProvider
func pasteboard(_ pasteboard: NSPasteboard?, item: NSPasteboardItem, provideDataForType type: String)
{
item.setString("Outline Pasteboard Item", forType: type)
}
}
From https://developer.apple.com/reference/appkit/nsoutlineview :
Each item in the outline view must be unique. In order for the
collapsed state to remain consistent between reloads the item's
pointer must remain the same and the item must maintain isEqual(_:)
sameness.
I was using Tuples (String, NSColor). And Tuples don't conform to the hashable protocol !
After switching from Tuples items to MyClass items, everything works fine !
(correct behaviour from the blue drag bar, and no blue rect when dragging)
class MyClass {
var name: String!
var color: NSColor!
init(_ _name: String, _ _color: NSColor) {
name = _name
color = _color
}
}

EXC_BAD_ACCESS in Simple NSOutlineView DataSource with Structs, but not with Classes

I am making a simple NSOutlineView and am having trouble with crashes and apparent non-deterministic behavior. Here's the code for my view controller.
import Cocoa
struct Hierarchy {
var name: String
var children: [String]
init(name: String, children: [String]) {
self.name = name
self.children = children
}
}
class MainViewController: NSViewController {
#IBOutlet weak var outlineView: NSOutlineView!
var data: [Hierarchy] = [Hierarchy]()
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
self.outlineView.delegate = self
self.outlineView.dataSource = self
self.data = [
Hierarchy(name: "Heading 1", children: ["Abc", "Def", "Ghi"]),
Hierarchy(name: "Heading 2", children: [String]()),
Hierarchy(name: "Heading 3", children: ["Jkl", "Mno", "Pqr"])
]
}
}
extension MainViewController: NSOutlineViewDataSource {
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if let heierarchy = item as? Hierarchy {
return heierarchy.children.count
}
return self.data.count
}
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
if let heierarchy = item as? Hierarchy {
return heierarchy.children[index]
}
return self.data[index]
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
if let heierarchy = item as? Hierarchy {
return heierarchy.children.count > 0
}
return false
}
}
extension MainViewController: NSOutlineViewDelegate {
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
var view: NSTableCellView?
if let hierarchy = item as? Hierarchy {
view = outlineView.make(withIdentifier: "AlphaCell", owner: self) as? NSTableCellView
if let textField = view?.textField {
textField.stringValue = hierarchy.name
textField.sizeToFit()
}
} else if let hierarchyChild = item as? String {
view = outlineView.make(withIdentifier: "AlphaCell", owner: self) as? NSTableCellView
if let textField = view?.textField {
textField.stringValue = hierarchyChild
textField.sizeToFit()
}
}
return view
}
}
This will either show nothing in the Outline View, crash when trying to expand one of the headings, or open one of the headings to reveal "Heading 1", "Heading 2", "Heading 3" inside, nested.
HOWEVER. If I change from structs to classes for Hierarchy, everything works. Why is this the case?
class Hierarchy {
var name: String
var children: [String]
init(name: String, children: [String]) {
self.name = name
self.children = children
}
}

Simple NSOutlineView Retain Crash

I've got a simple NSOutlineView setup in my OSX Swift project feeding from a basic array but its causing an EXC_BAD_ACCESS crash.
Having enabled zombies, it crashes with the following error:
[NSMutableIndexSet retain]: message sent to deallocated instance
Heeeelp! Here is my code:
class SidebarViewController: NSViewController, NSOutlineViewDataSource {
//MARK: Vars
#IBOutlet var sidebar : NSOutlineView?
var data : [String] = ["Assemblies", "Parts", "Customers"]
//MARK: Init
override func viewDidLoad()
{
super.viewDidLoad()
// Do view setup here.
}
//MARK: NSOutlineView Delegate / Datasource
func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int
{
return data.count
}
func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool
{
return false
}
func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject
{
return data[index]
}
func outlineView(outlineView: NSOutlineView, objectValueForTableColumn tableColumn: NSTableColumn?, byItem item: AnyObject?) -> AnyObject?
{
return item
}
}
Turns out that objectValueForTableColumn method require an obj_c object returned. So returning String in my array doesn't work. I changed this to NSString and it now works.

NSOutlineView, using item: AnyObject

I'm creating a NSOutlineView. When implementing the Data Source, although I'm able to create the top hierarchy I can not implement the childHierarchy. The reason is that I can't read the item: AnyObject? which prevents me from returning the right array from the dictionary.
//MARK: NSOutlineView
var outlineTopHierarchy = ["COLLECT", "REVIEW", "PROJECTS", "AREAS"]
var outlineContents = ["COLLECT":["a","b"], "REVIEW":["c","d"],"PROJECTS":["e","f"],"AREAS":["g","h"]]
//Get the children for item
func childrenForItem (itemPassed : AnyObject?) -> Array<String>{
var childrenResult = Array<String>()
if(itemPassed == nil){ //If no item passed we return the highest level of hirarchy
childrenResult = outlineTopHierarchy
}else{
//ISSUE HERE:
//NEED TO FIND ITS TITLE to call the correct child
childrenResult = outlineContents["COLLECT"]! //FAKED, should be showing the top hierarchy item so I could return the right data
}
return childrenResult
}
//Data source
func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject{
return childrenForItem(item)[index]
}
func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool{
if(outlineView.parentForItem(item) == nil){
return true
}else{
return false
}
}
func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int{
return childrenForItem(item).count
}
func outlineView(outlineView: NSOutlineView, viewForTableColumn: NSTableColumn?, item: AnyObject) -> NSView? {
// For the groups, we just return a regular text view.
if (outlineTopHierarchy.contains(item as! String)) {
let resultTextField = outlineView.makeViewWithIdentifier("HeaderCell", owner: self) as! NSTableCellView
resultTextField.textField!.stringValue = item as! String
return resultTextField
}else{
// The cell is setup in IB. The textField and imageView outlets are properly setup.
let resultTextField = outlineView.makeViewWithIdentifier("DataCell", owner: self) as! NSTableCellView
resultTextField.textField!.stringValue = item as! String
return resultTextField
}
}
}
I used this as a reference, although it's Objective-C implemented
You need to cast the item to the correct type for your outline. Generally you'd want to use a real data model, but for your toy problem with exactly two levels in the hierarchy, this suffices:
func childrenForItem (itemPassed : AnyObject?) -> Array<String>{
if let item = itemPassed {
let item = item as! String
return outlineContents[item]!
} else {
return outlineTopHierarchy
}
}