1

在 collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath 方法中,我试图将音频文件数组加载到集合视图单元格中,但基于 indexPath 行,它正在跳过索引 0 处的单元格,并在选择单元格时从索引 1 处的单元格开始播放音频文件。我无法理解为什么。

这是我的代码

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
audioArray =[[NSArray alloc] initWithObjects:@"0", @"1", @"2", @"3", 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];

}

如果有人能指出我正确的方向。我会感激的。

感谢帮助。

4

1 回答 1

3

终于修好了

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

if ([[segue identifier] isEqualToString:@"showDetail"])
{
    NSIndexPath *selectedIndexPath = [[self.collectionView indexPathsForSelectedItems] objectAtIndex:0];

    // load the image, prevent it from being cached using 'initWithContentsOfFile'

    NSString *imageNameToLoad = [NSString stringWithFormat:@"%d_full", selectedIndexPath.item];

    NSString *pathToImage = [[NSBundle mainBundle] pathForResource:imageNameToLoad ofType:@"jpg"];

    UIImage *image = [[UIImage alloc] initWithContentsOfFile:pathToImage];


    NSString *audioToLoad = [NSString stringWithFormat:@"%d", selectedIndexPath.item];


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

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

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

    DetailViewController *detailViewController = [segue destinationViewController];

    detailViewController.image = image;

    detailViewController.audioPlayer = audioPlayer;

               }        
            }

它可能对某人有所帮助。

于 2013-06-11T21:31:22.087 回答