Assignment #4 Task #6

Please note, this blog entry is from a previous course. You might want to check out the current one.

When the user chooses a photo from any list, display its image inside a scrolling view that allows the user to pan and zoom (a reasonable amount). You obtain the URL for a Flickr photo’s image using FlickrFetcher’s urlForPhoto:format: (use Large).

Inside your iPhone story board drag out a new view controller, add a scroll view and inside an image view. Create a new class for the view controller and connect outlets for the scroll and image view.

Now create a model to hold the photo data:

// PhotoViewController.h
@property (nonatomic, strong) NSDictionary *photo;

// PhotoViewController.m
@synthesize photo = _photo;

To get the photo we need an url which we can use to fetch the binary data of the photo to create an actual image. This image is pasted into the image view, which is set to the size of the image. The scroll view needs also the size of the image. For zooming we set the controller as delegate and adjust the scrolling settings.

- (void)viewDidLoad
    [super viewDidLoad];
    NSURL *url = [FlickrFetcher format:FlickrPhotoFormatLarge];
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    self.imageView.image = image;
    self.imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    self.scrollView.delegate = self;
    self.scrollView.zoomScale = 1.0;
    self.scrollView.maximumZoomScale = 10;
    self.scrollView.minimumZoomScale = 0.1;
    self.scrollView.contentSize = image.size;
    if (self.imageView.window) [self.imageView setNeedsDisplay];    

Now the delegate needs to know which view it should adjust when zooming:

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
    return self.imageView;

Finally we set the photo data for the segue from the table view controller:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    [super prepareForSegue:segue sender:sender];
    if ([segue.identifier isEqualToString:@"Show Photo"]) {
        [segue.destinationViewController setPhoto:
         [ objectAtIndex:
          [self.tableView indexPathForSelectedRow].row]];        

The complete code for this task is available at github.


Leave a Reply

Your email address will not be published.