IOS UICollectionView getting started 07 click cell to enlarge the image
In this section, you can click an image to enlarge the image.
First, we create a class named FlickrPhotoViewConroller, which inherits from UIViewController. Modify the header file as follows:
#import
@class FlickrPhoto;@interface FlickrPhotoViewConroller : UIViewController@property (nonatomic, strong) FlickrPhoto *flickrPhoto;@end
Declare outlet and action:
#import "FlickrPhotoViewConroller.h"#import "Flickr.h"#import "FlickrPhoto.h"@interface FlickrPhotoViewConroller ()@property (weak) IBOutlet UIImageView *imageView;- (IBAction)done:(id)sender;@end
Open the storyboard, add a UIViewController to the storyboard, and set the class of this view to FlickrPhotoViewConroller.
Use ctrl + drag to create a modal segue from the master view to the Flickr Photo view controller.
Select this segue and set its identifier to ShowFlickrPhoto.
Add a toolbar and an imageview to the view, modify the toolbar button title to Done, ctrl + drag connection button and the done: Method of the FlickrPhotoViewController.
Connect the outlet of the imageView:
Open ViewController. m and add the following code to the @ interface area:
@property (nonatomic) BOOL sharing;
Modify didSelectItemAtIndexPath:
if (!self.sharing) { NSString *searchTerm = self.searchs[indexPath.section]; FlickrPhoto *photo = self.searchResults[searchTerm][indexPath.row]; [self performSegueWithIdentifier:@"ShowFlickrPhoto" sender:photo]; [self.collectionView deselectItemAtIndexPath:indexPath animated:YES]; } else { }
When a user clicks a thumbnail, execute ShowFlickrPhoto segue.
#import "FlickrPhotoViewConroller.h"- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ if ([segue.identifier isEqualToString:@"ShowFlickrPhoto"]) { FlickrPhotoViewConroller *flickrPhotoViewController = segue.destinationViewController; flickrPhotoViewController.flickrPhoto = sender; }}
Implement the viewWillAppear method to display large images to the view:
-(void)viewDidAppear:(BOOL)animated { // 1 if(self.flickrPhoto.largeImage) { self.imageView.image = self.flickrPhoto.largeImage; } else { // 2 self.imageView.image = self.flickrPhoto.thumbnail; // 3 [Flickr loadImageForPhoto:self.flickrPhoto thumbnail:NO completionBlock:^(UIImage *photoImage, NSError *error) { if(!error) { // 4 dispatch_async(dispatch_get_main_queue(), ^{ self.imageView.image = self.flickrPhoto.largeImage; }); } }]; }}
To implement the done method, click the Done button to return to the main view:
- (void)done:(id)sender{ [self.presentingViewController dismissViewControllerAnimated:YES completion:^{}];}
The program execution result is as follows: