Friday, December 9, 2011

UIScrollView Quick Tutorial

Just for anyone who's keen on doing iOS programming. The scroll view is an integral part of anybody's app. You cannot do without it. So here goes.
Essentially a scrollview is just a container to put stuff in. Such as images, text, buttons, etc. Most commonly objects placed in a scrollView is an image. In this tutorial i will enhance on the scrollView using imageView. Imagine like a stack of blocks, the scrollView being at the bottom most layer, with the imageView on the second layer, finally the image on the top most layer on top of the imageview.

- (void)viewDidLoad
{
    [super viewDidLoad]; 
    //get image from directory and set up the imageview
    image = [UIImage imageNamed:@"elephant.png"];
    imageView = [[UIImageView alloc] initWithImage:image];
    //place imageview in scrollview
    UIScrollView* scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    scrollView.contentSize = CGSizeMake(image.size.width, image.size.height);
    scrollView.minimumZoomScale = 0.5;
    scrollView.maximumZoomScale = 3.0;
    scrollView.delegate = self;
    scrollView.scrollEnabled = YES;
    [scrollView addSubview:imageView];
    [self.view addSubview:scrollView];
 
  }
Note that the scrollview's content size has been set to the size of the image. A scrollview's scrollEnabled is default a YES, i set it to YES for demonstration purposes. Now notice that we have set the minimum and max zoom scale to a certain float number. This will not work if the delegate method isn't implemented. Hence, we implement the scrollview's delegate to "self", this allows us to access the delegate's methods which run in the scrollview class.
Now to allow pinching on this scrollview, we have to implement a scrollview delegate method.

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return imageView;
}
A pretty straightforward method to enable the resizing of the imageView and allow pinching on the scrollView. As pinching is a separate gesture defined in the iOS classes, we don't wanna have to implement the gesture personally. Hence the use of this method is pretty simple and it returns a resized imageView on the screen when pinched.
However, you will not get a centered image on screen. I will post this on top of this in the next post!

Cheers