Play music when I select UITableViewCell
I can show music library on UITableView.
songsArray = [[NSMutableArray alloc]init];
MPMediaQuery *playlistQuery = [[MPMediaQuery alloc开发者_StackOverflow]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]];
But I can't play music when I selected UITableView
Cell.
NSUInteger row = indexPath.row;
NSString *selectedSong = [songsArray objectAtIndex:row];
MPMusicPlayerController *appPlayer = [MPMusicPlayerController iPodMusicPlayer];
[appPlayer setQueueWithQuery:selectedSong];
[appPlayer play];
}
Ah I see the problem:
Move this code:
NSUInteger row = indexPath.row;
NSString *selectedSong = [songsArray objectAtIndex:row];
MPMusicPlayerController *appPlayer = [MPMusicPlayerController iPodMusicPlayer];
[appPlayer setQueueWithQuery:selectedSong];
[appPlayer play];
to the UITableViewDelegate protocol method 'didSelectRowAtIndexPath' like this:
- (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];
}
Edit
Documentation:
- UITableView Class Reference
- UITableViewDelegate Protocol Reference
- UITableViewDataSource Protocol Reference
- MPMusicPlayerController Class Reference
- MPMediaQuery Class Reference
- Using the iPod Library / iPod Library Access Programming Guide
精彩评论