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