Как я могу в NSOutlineView, привязанном к NSTreeController, управляемому NSXMLDocument, отображать только некоторые NSElements (того же типа), а не другие?
Спасибо
Как я могу в NSOutlineView, привязанном к NSTreeController, управляемому NSXMLDocument, отображать только некоторые NSElements (того же типа), а не другие?
Спасибо
Чтобы скрыть некоторые элементы, 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.