ios - 如何使用 NSArrays 的 NSDictionary 设置 TableView 的 titleForHeaderInSection 和 numberOfRowsInSection?

标签 ios objective-c uitableview nsarray nsdictionary

我有一个 NSDictionary 和 NSArrays 个名称,所以自然总共有 26 个数组。我想用数组的键设置 titleForHeaderInSection(A、B、C 等),用数组的计数设置 numberOfRowsInSection。我可以通过用 block 枚举每个数组来获取每个数组的计数,但是如何根据我拥有的 NSDictionary 在我的 TableView 上设置这两个选项?有什么方法可以对 NSDictionary 进行排序,以便结果按字母顺序排列吗?

这是我的 NSDictionary:

@{
    @"A" :  
        @[@"Person One", @"Person Two", @"Person Three"],
    @"B" :
        @[@"Person One", @"Person Two", @"Person Three", @"Person Four"],
    @"C" :
        @[@"Person One", @"Person Two"],
}
// etc

这是 NSDictionary 的 NSLog:标题是无序的吗?

A -- 23
B -- 78
G => 27
U => 1
H => 57
V => 6
I => 1
// etc

最佳答案

字典中的条目是无序的。你可以做的是创建一个数组 所有部分的标题并按字母顺序排序:

NSDictionary *dict = ...; // your dictionary
NSArray *sectionTitles = [[dict allKeys] sortedArrayUsingSelector:@selector(compare:)];

那么节数是

[sectionTitles count]

对于给定的节号,标题和行数可以计算为

NSString *title = sectionTitles[section];
NSUInteger numRows = [dict[sectionTitles[section]] count];

最后,对于给定的索引路径,对应的item是

NSString *item = dict[sectionTitles[indexPath.section]][indexPath.row];

关于ios - 如何使用 NSArrays 的 NSDictionary 设置 TableView 的 titleForHeaderInSection 和 numberOfRowsInSection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23276578/

相关文章:

ios - 蓝牙IOS : connectPeripheral results a didDisconnectPeripheral with null error SOMETIMES

iphone - 动画开始但似乎没有继续

iphone - 使用 UITabBarController 时在整个屏幕上覆盖一个 View ?

swift - 从 Firestore 填充 UITableView

ios - UITableViewCell 圆圈项目符号点

iphone - 如何在使用动画按下返回键时将新的 UITextField 添加到自定义 UITableViewCell

ios - NSPredicate 用于常规搜索

ios - UIImageView 图像未显示在 iPad 模拟器上

iphone - 为什么我不能在我的 iPhone 静态库中的包中加载 nib?

ios - 如果 iPhone 应用程序处于非事件状态,iPhone 应用程序可以响应通过 Apple Watch 传输的文件吗?