Filtering a NSTreeController with NSSearchField ?
Th开发者_如何学运维is question seemed to be asked before but was never answered. So is it possible to filter a NSTreeController with NSSearchField? If so, then how?
Thanks!
If your question is "can it be done in IB, just like NSArrayController using the bindings inspector?", then the answer is "No". Although IB suggests that the binding is possible (one can make the actual binding) it will generate an exception as NSTreeController has no predicate.
I suppose it should be possible by implementing subclasses although it would be a bit of a challenge as the filtering process will have impact on the tree structure of your data.
EDIT: It can actually be done with a bit of code. Presuming you have view controller set as the delegate for your NSSearchField, you implement the following method for your delegate:
- (void)controlTextDidEndEditing: (NSNotification *)aNotification {
NSPredicate *aPredicate = nil;
if ([[[self mySearchField] stringValue] isEqualToString:@""]) {
aPredicate = [NSPredicate predicateWithFormat: @"parent == nil"];
} else {
aPredicate = [NSPredicate predicateWithFormat:@"name contains[c] %@", [[self mySearchField] stringValue]];
}
[[self myTreeController] setFetchPredicate: aPredicate];
[[self myOutlineView] reloadData];
}
The above filters the tree based on a name attribute. Note that filtering a tree view can have strange effects on the tree structure. Also note that when an empty string is presented, the method creates the default predicate which filter the top level entries from the datasource and reinstates the tree view.
精彩评论