你解决了这个问题吗?
通过实现sectionIndexTitlesForTableView:来构建自己的部分标题数组,我已经成功地使部分标题索引正确显示:
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
NSMutableArray *indexKeys = [NSMutableArray arrayWithCapacity:30];
NSArray *fetchedResults = [fetchedResultsController fetchedObjects];
NSString *currKey = @"DEFAULT";
for (NSManagedObject *managedObject in fetchedResults) {
NSString *indexKey = [managedObject valueForKey:@"indexKey"];
if (![indexKey isEqualToString:currKey]) {
[indexKeys addObject:indexKey];
currKey = indexKey;
}
}
return indexKeys;
}
这里,indexKey是名称的第一个字母。
然而,在sectionForSectionIndexTitle中,这会创建两个问题之一:
如果我只返回该部分的索引,那么现在这是未排序的索引,不再与fetchResultController中的排序顺序对应:
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
return index;
}
另外,如果我将调用传递给fetchedResultsController,则会在非美国索引标题上中断,因为这些不再是fetchedResultsController使用的奇怪字符。
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
return [fetchedResultsController sectionForSectionIndexTitle:title atIndex:index];
}
当导航到“Ø”索引标题时,后面的代码会生成以下类型的错误:
由于未捕获的异常'NSInternalInconsistencyException',应用程序终止,原因是:索引标题在24处不等于'Ø'
解决此问题的方法是将有问题的字符转换回它们奇怪的形式:
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
if ([title isEqualToString:@"Æ"]) {
title = @"\u2206";
} else if ([title isEqualToString:@"Ø"]) {
title = @"\u0178";
} else if ([title isEqualToString:@"Å"]) {
title = @"\u2248";
}
return [fetchedResultsController sectionForSectionIndexTitle:title atIndex:index];
}
您可以在调试器中使用“打印描述到控制台”操作来查找Unicode值。
然而,更好的解决方案是找出为什么会发生这种奇怪的编码并加以防止。
willDisplayHeaderView
中使用localizedCapitalizedString
、localizedUppercaseString
或localizedLowercaseString
。(API_AVAILABLE ios 9.0) - ACAkgul