最新消息:iOS编程开发交流群(6906921) ,Mac.Cocoa开发交流群(7758675) 欢迎iOS/macOS开发编程爱好及学习者加入!

Cocoa开发之NSOutlineView点击headerTableColumn排序

macOS 天狐 8679浏览 0评论

实现点击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 就会自动排序了。

 

 

转载请注明:天狐博客 » Cocoa开发之NSOutlineView点击headerTableColumn排序

微信 OR 支付宝 扫描二维码
为天狐 打赏
非常感谢你的支持,哥会继续努力!
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址