Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

iOS Scroll View (Scroll View)

Use of Scroll Views

If the content exceeds the screen size, a scroll view is used to display the hidden parts.

It can contain all other user interface elements such as image views, labels, text views, and even another scroll view.

Important Properties

Important Methods



- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated



- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated

Important Delegate Methods

In ViewController.h, addthe scroll view and declare the scroll view to make the class conform to the delegate protocol, as follows:



#import 



@interface ViewController : UIViewController

{

    UIScrollView *myScrollView;

}    



@end

Add the custom method addScrollView



-(void)addScrollView{

    myScrollView = [[UIScrollView alloc]initWithFrame:

    CGRectMake(20, 20, 280, 420)];

    myScrollView.accessibilityActivationPoint = CGPointMake(100, 100);

    imgView = [[UIImageView alloc]initWithImage:

    [UIImage imageNamed:@"AppleUSA.jpg"]];

    [myScrollView addSubview:imgView];

    myScrollView.minimumZoomScale = 0.5;

    myScrollView.maximumZoomScale = 3;

    myScrollView.contentSize = CGSizeMake(imgView.frame.size.width,

    imgView.frame.size.height);

    myScrollView.delegate = self;

    [self.view addSubview:myScrollView];

}

Note: We must add an image named "AppleUSA1.jpg" to our project, which can be done by dragging the image into our navigation area, which lists our project files. The image should be taller than the device's height.

Implement the scrollView delegate in ViewController.m



 -(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{

    return imgView;

}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

    NSLog(@"Did end decelerating");

}    

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

//    NSLog(@"Did scroll");

}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView 

  willDecelerate:(BOOL)decelerate{

    NSLog(@"Did end dragging");

}

-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{

    NSLog(@"Did begin decelerating");

}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{

    NSLog(@"Did begin dragging");

}

Update viewDidLoad in ViewController.m as follows



(void)viewDidLoad

{

   [super viewDidLoad];

   [self addScrollView];

   //Do any additional setup after loading the view, typically from a nib

}

Output

Now when we run the application we will see the following output. Once you scroll the scroll view, you will be able to view the rest of the image:

scrollViewOutput