Wednesday, May 26, 2010

Creating scrollable view

These are the steps for creating an application with scrollable view:
1. Create a scrollable view in the application
  • use either interface builder or code to add a UIScrollView to the current window
  • Sample code to add a scroll view:
            CGRect frame = [CGRectMake(0,0,200,200)];
            UIScrollView* scrollView = [[UIScrollView alloc] initWithFrame:frame];


2. Add subviews (frames may extend beyond the above scroll view bounds)
  • Sample code to add subview:


        UIImage* image = [UIImage withName: @"image.jpg"];  /// image.jpg need to be added to resource
             UIImageView imageView = [[UIImageView alloc] initWithImage:image];
             [scrollView addSubview: imageView];


3. Set the content size
  • sample code to set content size:
             [scrollView setContentSize: [image size]];

4. Set the max zoom and min zoom, if zoom is needed
  • sample code to set min and max zoom:
             [scrollView setMaximumZoomScale: 4.0];
             [scrollView setMinimumZoomScale: 0.1];


5. If zoom is needed, implement the ScrollView's viewForZoomingInScrollView delegate
  • sample code for viewForZoomingInScrollView delegate:
             - (UIView *) viewForZoomingInScrollView: (UIScrollView *) scrollView  {
                       return imageView;
             }
6. Implement all the needed and optional delegate if neccessary.
  • Implement scrollViewDidScroll delegate if need to respond to scroll event
    • sample code:
                          - (void) scrollViewDidScroll: (UIScrollView *)scrollView  {
                              if (scrollView.contentOffset ...) {
                                      // do something here
                                }
                          }
  • Set the scrollViewShouldScrollToTop delegate to change the behaviour
    • sample code:
               - (BOOL) scrollViewShouldScrollToTop: (UIScrollView *) scrollView {
                         // return TRUE or FALSE, depending on view should scroll to top
               }

7. When the view is no more needed, to allow user to return to previous view, send the removeFromSuperview message to the viewController.
    • sample code:
      [self.view removeFromSuperview];

No comments:

Post a Comment