不幸的是,我目前在笔记本电脑上没有互联网,因此我将不得不描述自己的代码,因为我有可变的字母顺序排列的歌曲标题。我有一个uitableview当前正在显示这些,但是我想在表的侧面有节头和字母索引,因此我需要将这些歌曲放入nsdictionary中进行显示,但是我无法找到一种有效的方法在nsdictionary中将数组排序为按字母顺序排列的部分(也有一个#部分,我将其做成nshead的nsarray)。
答案 0 :(得分:0)
有很多准备数据的可能性。但是,由于您的歌曲已经排序,因此视图控制器可能看起来像这样:
@interface TableViewController ()
@property (strong, nonatomic) NSArray *sectionTitles;
@property (strong, nonatomic) NSArray *songsInSections;
@end
@implementation TableViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *songs = @[@"A song", @"Another song", @"Some other song", @"Yet another song"];
// store all the needed section titles
NSMutableArray *sectionTitles = [NSMutableArray array];
// store the songs in sections (arrays in array)
NSMutableArray *songsInSections = [NSMutableArray array];
// prepare the data for the table view
for (NSString *song in songs) {
// get the song's section title (first letter localized and uppercased)
NSString *sectionTitle = [[song substringToIndex:1] localizedUppercaseString];
// check if a section for the song's section title has already been created and create one if needed
if (sectionTitles.count == 0 || ![sectionTitle isEqualToString:sectionTitles[sectionTitles.count - 1]]) {
// add the section title to the section titles array
[sectionTitles addObject:sectionTitle];
// create an (inner) array for the new section
[songsInSections addObject:[NSMutableArray array]];
}
// add the song to the last (inner) array
[songsInSections[songsInSections.count - 1] addObject:song];
}
// "store" the created data to use it as the table view's data source
self.sectionTitles = sectionTitles;
self.songsInSections = songsInSections;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self.songsInSections count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return self.sectionTitles[section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.songsInSections[section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
cell.textLabel.text = self.songsInSections[indexPath.section][indexPath.row];
return cell;
}
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return self.sectionTitles;
}
@end