实现点击NSOutlineView的header后出现排序箭头,并且数据源排序。
NSOutlineView点击header排序比NSTableView复杂,NSOutlineView的数据源通常来说不是一个数组而是一个node实体。
NSOutlineView的tableColumns中保存着所有的列信息,可以遍历,也可以根据key获取某一个tableColumn。
tableColumn有一个setSortDescriptorPrototype方法用来设置排序NSSortDescriptor(暂且成为排序器)。
数据node结构如下
@interface ProfilesNode : NSObject @property (nonatomic, weak)ProfilesNode *rootNode; @property (nonatomic, strong)NSArray *childrenNodes; @property (nonatomic, copy)NSString *key; //@property (nonatomic, copy)NSString *name; @property (nonatomic, copy)NSString *detail; @property (nonatomic, copy)NSString *type; @property (nonatomic, copy)NSString *uuid; @property (nonatomic, copy)NSString *filePath; @property (nonatomic, strong)NSDictionary *extra; @property (nonatomic, copy)NSString *expirationDate; @end
1.方法一
在- (void)viewDidLoad中为所有tableColumn或者指定column设置NSSortDescriptor。
for (NSTableColumn *tableColumn in self.treeView.tableColumns ) {
NSSortDescriptor *sortStates = [NSSortDescriptor sortDescriptorWithKey:tableColumn.identifier
ascending:NO comparator:^(id obj1, id obj2) {
return [obj1 compare:obj2];
}];
[tableColumn setSortDescriptorPrototype:sortStates];
}
实现delegate
- (void)outlineView:(NSOutlineView *)outlineView sortDescriptorsDidChange:(NSArray<NSSortDescriptor *> *)oldDescriptors{
NSSortDescriptor *sortDescriptor = [[outlineView sortDescriptors] objectAtIndex:0];
NSArray *sortedArray;
NSMutableArray *currChildren= [_rootNode.childrenNodes mutableCopy];
sortedArray = [currChildren sortedArrayUsingDescriptors:@[sortDescriptor]];
_rootNode.childrenNodes = sortedArray;
[outlineView reloadData];
}
这时候点击header 就会自动排序了。