這一節,我們實現通過點擊圖片將圖片放大顯示的功能。
首先我們創建一個名為FlickrPhotoViewConroller的類,這個類繼承於UIViewController。修改頭文件內容如下:
#import@class FlickrPhoto; @interface FlickrPhotoViewConroller : UIViewController @property (nonatomic, strong) FlickrPhoto *flickrPhoto; @end
#import "FlickrPhotoViewConroller.h" #import "Flickr.h" #import "FlickrPhoto.h" @interface FlickrPhotoViewConroller () @property (weak) IBOutlet UIImageView *imageView; - (IBAction)done:(id)sender; @end打開storyboard,添加一個UIViewController到storyboard中,設置這個view的class為FlickrPhotoViewConroller。
從主view使用ctrl+drag創建一個到Flickr Photo view controller的modal segue。
選中這個segue,設置其identifier為ShowFlickrPhoto
添加一個toolbar和一個imageview到view中,修改toolbar按鈕標題為Done,ctrl+drag連接按鈕和FlickrPhotoViewController的done:方法。
再將imageView的outlet也連接上:
打開ViewController.m,添加以下代碼到@interface區域中:
@property (nonatomic) BOOL sharing;
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 { }當用戶點擊某幅縮略圖時,執行ShowFlickrPhoto segue。
#import "FlickrPhotoViewConroller.h" - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"ShowFlickrPhoto"]) { FlickrPhotoViewConroller *flickrPhotoViewController = segue.destinationViewController; flickrPhotoViewController.flickrPhoto = sender; } }實現viewWillAppear方法,顯示大圖片到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; }); } }]; } }實現done方法,通過點擊Done按鈕返回到主view:
- (void)done:(id)sender { [self.presentingViewController dismissViewControllerAnimated:YES completion:^{}]; }