这一节,我们实现通过点击图片将图片放大显示的功能。
首先我们创建一个名为FlickrPhotoViewConroller的类,这个类继承于UIViewController。
改动头文件内容例如以下:
#import声明outlet和action:@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中,改动toolbarbutton标题为Done,ctrl+drag连接button和FlickrPhotoViewController的done:方法。
再将imageView的outlet也连接上:
打开ViewController.m。加入下面代码到@interface区域中:
@property (nonatomic) BOOL sharing;改动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 { }当用户点击某幅缩略图时,运行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方法。通过点击Donebutton返回到主view:
- (void)done:(id)sender{ [self.presentingViewController dismissViewControllerAnimated:YES completion:^{}];}程序运行效果例如以下: