我可以在UITableView上显示音乐库。
songsArray = [[NSMutableArray alloc]init];
MPMediaQuery *playlistQuery = [[MPMediaQuery alloc]init];
[playlistQuery setGroupingType:MPMediaGroupingTitle];
songArray = [playlistQuery items];
for (MPMediaItem *song in songArray) {
NSString *songTitle = [song valueForProperty: MPMediaItemPropertyTitle];
[songsArray addObject:songTitle];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
cell.textLabel.text = [songsArray objectAtIndex:row];
[cell.textLabel setTextColor:[UIColor whiteColor]];
但是当我选择UITableView
Cell时,我无法播放音乐。
NSUInteger row = indexPath.row;
NSString *selectedSong = [songsArray objectAtIndex:row];
MPMusicPlayerController *appPlayer = [MPMusicPlayerController iPodMusicPlayer];
[appPlayer setQueueWithQuery:selectedSong];
[appPlayer play];
}
啊,我看到了问题:
移动此代码:
NSUInteger row = indexPath.row;
NSString *selectedSong = [songsArray objectAtIndex:row];
MPMusicPlayerController *appPlayer = [MPMusicPlayerController iPodMusicPlayer];
[appPlayer setQueueWithQuery:selectedSong];
[appPlayer play];
到这个UITableViewDelegate协议方法'didSelectRowAtIndexPath':
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = indexPath.row;
NSString *selectedSong = [songsArray objectAtIndex:row];
MPMusicPlayerController *appPlayer = [MPMusicPlayerController iPodMusicPlayer];
[appPlayer setQueueWithQuery:selectedSong];
[appPlayer play];
}
编辑
文档: