Давайте назовем ваш UITableViewController
класс LibraryArtistsBrowserTableViewController
1. Подготовка
Файл интерфейса LibraryArtistsBrowserTableViewController.h будет содержать следующие переменные:
@interface LibraryArtistsBrowserTableViewController : UITableViewController
@property (nonatomic, strong) MPMediaQuery *artistsQuery;
@property (nonatomic, strong) NSArray *artistsArray,*sectionedArtistsArray;
@property (nonatomic, strong) UILocalizedIndexedCollation *collation;
- (NSArray *)partitionObjects:(NSArray *)array collationStringSelector:(SEL)selector;
@end
2. Индексация
В вашем файле реализации LibraryArtistsBrowserTableViewController.m вставьте следующий код в ваш viewDidLoad
метод:
- (void)viewDidLoad
{
[super viewDidLoad];
//Make a query for artists
self.artistsQuery = [MPMediaQuery artistsQuery];
//Group by Album Artist
[self.artistsQuery setGroupingType:MPMediaGroupingAlbumArtist];
//Grab the "MPMediaItemCollection"s and store it in "artistsArray"
self.artistsArray = [self.artistsQuery collections];
//We then populate an array "artists" with the individual "MPMediaItem"s that self.artistsArray` contains
NSMutableArray *artists = [NSMutableArray array];
for (MPMediaItemCollection *artist in artistsArray) {
//Grab the individual MPMediaItem representing the collection
MPMediaItem *representativeItem = [artist representativeItem];
//Store it in the "artists" array
[artists addObject:representativeItem];
}
//We then index the "artists" array and store individual sections (which will be the alphabet letter and a numbers section), all containing the corresponding MPMediaItems
self.sectionedArtistsArray = [self partitionObjects:artists collationStringSelector:@selector(albumArtist)];
}
Функция, которую мы используем для разделения элементов, определена ниже, поместите ее где-нибудь в файл вашей реализации:
- (NSArray *)partitionObjects:(NSArray *)array collationStringSelector:(SEL)selector
{
self.collation = [UILocalizedIndexedCollation currentCollation];
NSInteger sectionCount = [[collation sectionTitles] count];
NSMutableArray *unsortedSections = [NSMutableArray arrayWithCapacity:sectionCount];
for(int i = 0; i < sectionCount; i++)
[unsortedSections addObject:[NSMutableArray array]];
for (id object in array)
{
NSInteger index = [self.collation sectionForObject:object collationStringSelector:selector];
[[unsortedSections objectAtIndex:index] addObject:object];
}
NSMutableArray *sections = [NSMutableArray arrayWithCapacity:sectionCount];
for (NSMutableArray *section in unsortedSections)
[sections addObject:[self.collation sortedArrayFromArray:section collationStringSelector:selector]];
return sections;
}
Затем мы проверяем, знает ли контроллер представления, сколько разделов и строк в каждом разделе, наряду с заголовками каждого раздела (индексированные буквы / цифры):
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [[self.collation sectionTitles] objectAtIndex:section];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [self.collation sectionIndexTitles];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[self.collation sectionTitles] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[self.sectionedArtistsArray objectAtIndex:section] count];
}
3. Показаны художники
Затем мы показываем художников следующим образом:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
//We grab the MPMediaItem at the nth indexPath.row corresponding to the current section (or letter/number)
MPMediaItem *temp = [[self.sectionedArtistsArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
//Title the current cell with the Album artist
cell.textLabel.text = [temp valueForProperty:MPMediaItemPropertyAlbumArtist];
return cell;
}
Тебе должно быть хорошо идти. Единственная проблема, с которой я сталкиваюсь, заключается в том, что она не может избежать пунктуации (апострофы и т. Д.) И префикса художников «The». Кроме этого он работает просто отлично.