从NSOutlineView或NSTreeController中删除显示中的NSElements

时间:2015-07-15 14:21:55

标签: cocoa cocoa-bindings nsoutlineview nstreecontroller nsxmldocument

在NSOutlineView中,如果绑定到NSTreeController,由NSXMLDocument驱动,我只能显示一些NSElements(相同类型)而不显示其他NSElements?

由于

1 个答案:

答案 0 :(得分:0)

要隐藏某些元素,NSXMLElement必须进行子类化。目的是测试一个元素中的一个子元素是否是隐藏的元素之一,并将其​​从children数组中删除:

class ICoderElement:NSXMLElement{

    ///List of elements names to remove
    let nodeElementsNamesToRemove = ["title", "code"]

    override var children: [AnyObject]? {

        //get the array with all the children
        var superChildren = super.children

        //Cast the array of children to its true self
        if var trueSuperChildren = superChildren as? [NSXMLNode] {

            //Test if the array isn't empty to don't iterate over it
            if trueSuperChildren.count > 0 {

                //Iterate each of them
                for var index = 0; index < trueSuperChildren.count; index++ {
                    let node = trueSuperChildren[index]

                    //If any it's of NSXMLElement class unwarps it's name and...
                    if let nodeElement = node as? NSXMLElement, let nodeName = nodeElement.name {

                        //..tests if it's name it's o the list of elements to remove
                        //change to nodeElementsNamesToRemove.contains(nodeName) in swift2
                        if contains(nodeElementsNamesToRemove, nodeName) {

                            //Remove the child NSXMLElement from the array
                            trueSuperChildren.removeAtIndex(index)

                            //reduce the index as the array 1 less element
                            index = index - 1
                        }
                    }
                }
            }
            //returns the array without the selected elements
            return trueSuperChildren
        }
        return superChildren
    }
}

要使用此类,NSXMLDocument也必须进行子类化,以便可以用NSXMLElement替换:

class ICoderXMLDocument:NSXMLDocument {
    override class func replacementClassForClass(cls: AnyClass) -> AnyClass! {

        //Replace NSXMLElement by ICoderElement
        if cls === NSXMLElement.self {

            return ICoderElement.self
        }
        return cls
    }
}

从现在起,应谨慎使用childCount。它仍将返回XML文件中的子节点数。

因为这些元素只是隐藏的,所以仍然可以使用elementsForName等函数。