-->

I have a UICollectionView and i want to show an im

2020-07-30 04:00发布

问题:

I have a UICollectionViewController (with a navigation controller) and i want to show an image in a Cell that 'pushes' to a normal ViewController (different by every image). How do i do that?

回答1:

Seem you want to build photo gallery by UICollectionView. If use storyBoard, use segue

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

        // load the image, to prevent it from being cached we use 'initWithContentsOfFile'
        NSString *imageNameToLoad = [NSString stringWithFormat:@"%d_full", selectedIndexPath.row];
        NSString *pathToImage = [[NSBundle mainBundle] pathForResource:imageNameToLoad ofType:@"JPG"];
        UIImage *image = [[UIImage alloc] initWithContentsOfFile:pathToImage];

        DetailViewController *detailViewController = [segue destinationViewController];
        detailViewController.image = image;
    }
}

If use nib: inside didSelectItemAtIndexPath, use self.navigationController push.

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSString *imageNameToLoad = [NSString stringWithFormat:@"%d_full", indexPath.row];
    NSString *pathToImage = [[NSBundle mainBundle] pathForResource:imageNameToLoad ofType:@"JPG"];
    UIImage *image = [[UIImage alloc] initWithContentsOfFile:pathToImage];
    DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    detailViewController.image = image;
    [self.navigationController pushViewController:detailViewController animated:YES];
}

Sample code from Apple: https://developer.apple.com/library/ios/#samplecode/CollectionView-Simple/Introduction/Intro.html

CollecionView tutorial: http://www.raywenderlich.com/22324/beginning-uicollectionview-in-ios-6-part-12