0

I have loaded images and labels to custom collectionview cells in this method

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;


Cell *cell = [cv dequeueReusableCellWithReuseIdentifier:kCellID forIndexPath:indexPath];

Giving the cells title based on actual NSIndexPath value in the same method

cell.label.text = [NSString stringWithFormat:@"{%ld,%ld}", (long)indexPath.row, (long)indexPath.section];

Loading different images in each cell of the custom collection view cells in the same method

NSString *imageToLoad = [NSString stringWithFormat:@"%d.jpg", indexPath.row];

cell.image.image = [UIImage imageNamed:imageToLoad];

I want to load different audio files in each cell of the custom collection view cells in the same method

audioArray =[[NSArray alloc] initWithObjects:@"Theme1", @"Theme2", @"Theme3", @"Theme4", nil];

NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:filePath ofType: @"mp3"];

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: audioFilePath];

audioPlayer = [[AVAudioPlayer alloc]
               initWithContentsOfURL:fileURL error:nil];

If i add indexPath.row below

NSString *filePath = [audioArray objectAtIndex:indexPath.row];

Then it always plays "Theme4" last audio file from within the array in all cells

And if i write 0

NSString *filePath = [audioArray objectAtIndex:0];

Then it plays always "Theme1" the very first audio file in all cells

How i can load different audio files in each cell of the custom collection view cells.

Thanks for help.

4

1 回答 1

1

您应该将这些代码行添加到

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath


audioArray =[[NSArray alloc] initWithObjects:@"Theme1", @"Theme2", @"Theme3", @"Theme4", nil];

NSString *filePath = [audioArray objectAtIndex:indexPath.row];

NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:filePath ofType: @"mp3"];

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: audioFilePath];

audioPlayer = [[AVAudioPlayer alloc]
           initWithContentsOfURL:fileURL error:nil];
}

而不是在

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;

希望这可以帮助。

于 2013-06-10T18:59:10.117 回答