【发布时间】:2015-07-03 08:36:57
【问题描述】:
第一次在网站上提问。我一直在尝试通过将绑定从情节提要中取出并尝试在代码中重现效果来了解有关与 NSArrayController 相关的 NSTableView 绑定的更多信息。我可以使用绑定配置 NSTableView 和 NSArrayController 的初始排序顺序,但我似乎仍然无法在单击列时对其进行排序。
背景是我在故事板中有一个标准的、基于单元的 NSTableView,它通过 IBOutlet 绑定到 NSViewController。 NSViewController 有以下 viewDidLoad 方法:
- (void)viewDidLoad
{
[super viewDidLoad];
//setup the array controller
self.arrayController = [NSArrayController new];
[self.arrayController addObject:@{@"namef": @"Test1", @"namel": @"a"}];
[self.arrayController addObject:@{@"namef": @"Test2", @"namel": @"b"}];
[self.arrayController addObject:@{@"namef": @"Test3", @"namel": @"c"}];
[self.arrayController addObject:@{@"namef": @"Test4", @"namel": @"B"}];
//setup the table view column bindings and sorting
[[self.tableView tableColumnWithIdentifier:@"0"] bind:NSValueBinding toObject:self.arrayController withKeyPath:@"arrangedObjects.namef" options:nil];
[[self.tableView tableColumnWithIdentifier:@"0"] setSortDescriptorPrototype:[NSSortDescriptor sortDescriptorWithKey:@"namef" ascending:YES selector:@selector(caseInsensitiveCompare:)]];
[[self.tableView tableColumnWithIdentifier:@"1"] bind:NSValueBinding toObject:self.arrayController withKeyPath:@"arrangedObjects.namel" options:nil];
[[self.tableView tableColumnWithIdentifier:@"1"] setSortDescriptorPrototype:[NSSortDescriptor sortDescriptorWithKey:@"namel" ascending:YES selector:@selector(caseInsensitiveCompare:)]];
//Bind the array controller to the tableView
[self.tableView bind:NSContentBinding toObject:self.arrayController withKeyPath:@"arrangedObjects" options:nil];
[self.tableView bind:NSSelectionIndexesBinding toObject:self.arrayController withKeyPath:@"selectionIndexes" options:nil];
//setup sorting
[self.tableView setSortDescriptors:[NSArray arrayWithObject: [[NSSortDescriptor alloc] initWithKey:@"namel" ascending:YES selector:@selector(caseInsensitiveCompare:)]]];
[self.arrayController bind:NSSortDescriptorsBinding toObject:self withKeyPath:@"sortDescriptors" options:nil];
[self.arrayController setAutomaticallyRearrangesObjects:YES];
}
这会导致成功加载屏幕,其中表格视图按“名称”数据排序,并且每个列标题显示为可点击,每次点击时箭头向上/向下。
但是,排序顺序并没有改变...
阅读各种其他文章和 stackoverflow 问题,我看到了诸如“您只需将列绑定到数组控制器,NSTableView 将自动绑定自身”之类的答案以及经常涉及情节提要的各种其他解释。
我尝试了注释掉以下代码组件的各种组合。我尝试更改每列中 sortDescriptorPrototypes 内的文本。
我知道我遗漏了一条重要线索,而且这方面的文档很糟糕。谁能看到我做错了什么?如何正确绑定,以便单击列标题实际对数据进行排序?
【问题讨论】:
-
感谢 @Cristik 帮助我提高问题的质量
标签: objective-c macos cocoa nstableview nsarraycontroller