Sunday, November 16, 2014

iOS Tutorial - Part 24 - UIScrollView

UIScrollView


Video Description 
When the contents of a view is not fit inside of the device size we need to use scroll view. We can easily drag and drop it inside of our view controller. Then setting the content size of the scroll view with setContentSize method.

contentSize

If you are setting the content size of the scroll view equal to a view element, make sure that the view element size is set by that time. For example for imageView, we should set the scroll view size after imageView gets its image, like bellow.
    UIImage *img = [[UIImage alloc] initWithData:dataImage];
    [self.imageView setImage:img];
    self.scrollView.contentSize = self.imageView.image.size;

minimumZoomScale and maximumZoomScale

In order to add zooming feature to the scrollView we need to set the min and max zoom scale. minimumZoomScale indicates the least scale that user can zoom out (0 to 1). maximumZoomScale indicates maximum scale that user can zoom in to the picture.
   self.scrollView.minimumZoomScale = 0.2;
   self.scrollView.maximumZoomScale = 3.0;
A good place for setting these properties are in the scrollView setter, like bellow:
- (void)setScrollView:(UIScrollView *)scrollView
{
    _scrollView = scrollView;
    _scrollView.minimumZoomScale = 0.2;
    _scrollView.maximumZoomScale = 3.0;
}
If you run the program it will not work because we have to define "Which view we want to zoom in scrollView". We indicate this view by implementing one of UIScrollViewDelegate method (viewForZoomingInScrollView). Before implementing this delegate method don't forget to add the name of the delegate method in front of interface like <UIScrollViewDelegate> and setting delegate equal to self. We can add it in scrollView setter like bellow:
- (void)setScrollView:(UIScrollView *)scrollView
{
    _scrollView = scrollView;
    _scrollView.minimumZoomScale = 0.2;
    _scrollView.maximumZoomScale = 3.0;
    _scrollView.delegate = self;
}

viewForZoomingInScrollView

Inside of this delegate method we just return the view that we want to be able to zoom. In our example it's imageView, so the implementation would look like:
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imageView;
}

zoomScale

In order to set the scale of zoom programmatically we can use this property. For example if we want to have the zoom scale of 1 (Actual size) we have:
self.scrollView.zoomScale = 1.0;

flashScrollIndicators

We don't have scroll bars on the screen all the times. We can show them for a moment. In order to flash the scroll bars for the user you can use flashScrollIndicators method like bellow:
[self.scrollView flashScrollIndicators];

Download

Download this App from here

No comments:

Post a Comment