【问题标题】:Column data sorting in tableview表格视图中的列数据排序
【发布时间】:2013-11-08 11:03:14
【问题描述】:

我使用的表格视图看起来像 excel 表格类型可以说多列。在列标题上添加平移手势以增加列的宽度,就像在 Excel 表中一样。我在对列数据进行排序时遇到问题。列数据始终按字母/字符串格式排序。虽然我有一些数字类型的列以及日期类型。所以所有的列都被排序为一个字符串。 您能否建议一些选项来实现这一点。我将数组中的所有数据作为 Web 服务的字典。

让我分享一些排序代码。

-(void)sortTableDataUsingSortKey:(NSString *)sortKey withAscending:(BOOL)isAscending {

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:isAscending selector:@selector(compare:)];

    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    NSArray *arrTemp = [[NSArray alloc] initWithArray:[data_array sortedArrayUsingDescriptors:sortDescriptors]];
    [data_array count]?[data_array removeAllObjects]:NSLog(@"Datsource Table Not null");
    [data_array addObjectsFromArray:arrTemp];
    arrTemp = nil;

    [_table_view reloadData];
}

【问题讨论】:

  • 请添加一些针对不同数据类型使用sortKey参数的示例。
  • 我解决了这个问题。我只是根据字典的数据类型添加了条件排序描述符方法。并在 Data_array 字典中添加了正确数据类型的数据。就像数据是数字一样,然后将它们作为数字/浮点数或 NSDate 添加到字典中。
  • if ([data_array count] && [[[data_array objectAtIndex:0] valueForKey:sortKey] isKindOfClass:[NSString class]]) { sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending 选择器:@selector(caseInsensitiveCompare:)]; } else { sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:isAscending 选择器:@selector(compare:)]; }
  • 很高兴听到这个消息,请将其写为答案并接受它。

标签: ios sorting nsarray nssortdescriptor


【解决方案1】:

我解决了这个问题。我只是根据字典的数据类型添加了条件排序描述符方法。并在要添加数据的 Data_array 字典中。以适当的数据类型添加数据。就像数据是数字一样,然后将它们作为数字/浮点数或 NSDate 添加到字典中。

现在我根据排序列检查字典中的数据类型。并更改排序选择器(比较非字符串数据和使用 caseInsensitiveCompare 的字符串数据:)其余工作正常。

最终可行的方法现在是 ..

-(void)sortTableDataUsingSortKey:(NSString *)sortKey withAscending:(BOOL)isAscending {
    NSSortDescriptor *sortDescriptor = nil;

    if ([data_array count] && [[[data_array objectAtIndex:0] valueForKey:sortKey] isKindOfClass:[NSString class]]) {
            sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:isAscending selector:@selector(caseInsensitiveCompare:)];
        }
        else {
            sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:isAscending selector:@selector(compare:)];
        }

    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    NSArray *arrTemp = [[NSArray alloc] initWithArray:[data_array sortedArrayUsingDescriptors:sortDescriptors]];
    [data_array count]?[data_array removeAllObjects]:NSLog(@"Datsource Table Not null");
    [data_array addObjectsFromArray:arrTemp];
    arrTemp = nil;

    [_table_view reloadData];
}

【讨论】:

    猜你喜欢
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多