2015-11-01 77 views
0

我正在創建一個NSOutlineView。在實現數據源時,儘管我可以創建頂層,但我無法實現childHierarchy。原因是我無法閱讀項目:AnyObject?,它阻止我從字典中返回正確的數組。NSOutlineView,使用項目:AnyObject

//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 
    } 

} 

}

我用這個作爲參照,雖然它的Objective-C的implemented

回答

0

您需要的item轉換爲正確的類型爲您的輪廓。通常你想使用一個真正的數據模型,但對你的玩具問題,在層次結構中正好有兩個層次,這足夠了:

func childrenForItem (itemPassed : AnyObject?) -> Array<String>{ 
    if let item = itemPassed { 
     let item = item as! String 
     return outlineContents[item]! 
    } else { 
     return outlineTopHierarchy 
    } 
} 
+0

完美的作品,非常感謝! – MMV

相關問題