iOS Scroll View | Tutorial
Usage of Scroll View
If the content exceeds the size of the screen, a scroll view is used to display the hidden parts.
It can contain all other UI elements such as image views, labels, text views, even another scroll view.
Important Properties
- contentSize
- contentInset
- contentOffset
- delegate
Important Methods
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated
- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated
Important Delegate Methods
In ViewController.h, add the scroll view and declare that the scroll view lets the class conform to the delegate protocol, as shown below:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UIScrollViewDelegate>{
UIScrollView *myScrollView;
}
@end
Add custom method addScrollView
-(void)addScrollView{
myScrollView = [initWithFrame: CGRectMake(20, 20, 280, 420)];
myScrollView.accessibilityActivationPoint = CGPointMake(100, 100);
imgView = [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, where our project files are listed. The image should be taller than the device height.
Implement 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 {
;
;
// 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 we scroll the scroll view, we will be able to view the rest of the image:
YouTip