iOS ScrollView Example with Paging

UIScrollView lets a user display content that is larger than the device window. You can create a Scroll View either programmatically or using the Interface Builder. Setting up a scroll view is easy, all you have to do a put other views inside the scroll view and set the size of the scroll view using the contentSize property. As long as the size of the scroll views is bigger than the screen window it will scroll. But its always recommended to set the scroll view width or the height same as the window so that scroll happens only in one direction such as horizontally or vertically for better user experience.

You can create a paging scroll view by setting the pagingEnabled property to true. In addition to that the scroll view can be positioned to a specific page in case there is paging or to a given origin using the contentOffset property or the setContentOffset method. It has a bunch of delegate methods to notify us about the state of the view such as
  • scrollViewDidScroll 
    • Gets called when the contents of the scroll view get scrolled. 
  • scrollViewDidEndDecelerating 
    • Gets called when the contents stop scrolling. 
  • scrollViewWillEndDragging 
    • Gets called when the dragging is finished. Dragging not same as scrolling basically the user moves the finger from one to location to another without giving any momentum to the move. 
In this example we generate the scroll view programmatically and add some other views such as labels and text. Also we create about 10 pages and set the paging to true. When the user scrolls or drags we listen to the delegate methods and then try to calculate the page number they are on and print that to the console log.

iOS ScrollView Example with horizontal scrolling
iOS ScrollView with paging enabled

Interface file for the view controller - MyScrollViewController.h

#import <UIKit/UIKit.h>

@interface UITextFieldViewController : UIViewController <UIScrollViewDelegate>

@property (nonatomic, strong) UIScrollView *myScrollView;

@end

Implementation file for the view controller - MyScrollViewController.m

#import "UITextFieldViewController.h"

@interface UITextFieldViewController ()

@end

@implementation UITextFieldViewController

@synthesize myScrollView;

- (void)viewDidLoad
{
    [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.
    
    //set the background to white color
    self.view.backgroundColor = [UIColor whiteColor];
    
    //initialize and allocate your scroll view
    self.myScrollView = [[UIScrollView alloc]
                         initWithFrame:CGRectMake(0, 0,
                                    self.view.frame.size.width,
                                    self.view.frame.size.height)];
    //set the paging to yes
    self.myScrollView.pagingEnabled = YES;
    
    //lets create 10 views
    NSInteger numberOfViews = 10;
    for (int i = 0; i < numberOfViews; i++) {
        
        //set the origin of the sub view
        CGFloat myOrigin = i * self.view.frame.size.width;
        
        //create the sub view and allocate memory
        UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(myOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)];
        //set the background to white color
        myView.backgroundColor = [UIColor whiteColor];
        
        //create a label and add to the sub view
        CGRect myFrame = CGRectMake(10.0f, 10.0f, 200.0f, 25.0f);
        UILabel *myLabel = [[UILabel alloc] initWithFrame:myFrame];
        myLabel.text = [NSString stringWithFormat:@"This is page number %d", i];
        myLabel.font = [UIFont boldSystemFontOfSize:16.0f];
        myLabel.textAlignment =  NSTextAlignmentLeft;
        [myView addSubview:myLabel];
        
        //create a text field and add to the sub view
        myFrame.origin.y += myFrame.size.height + 10.0f;
        UITextField *myTextField = [[UITextField alloc] initWithFrame:myFrame];
        myTextField.borderStyle = UITextBorderStyleRoundedRect;
        myTextField.placeholder = [NSString stringWithFormat:@"Enter data in field %i", i];
        myTextField.tag = i+1;
        [myView addSubview:myTextField];
        
        //set the scroll view delegate to self so that we can listen for changes
        self.myScrollView.delegate = self;
        //add the subview to the scroll view
        [self.myScrollView addSubview:myView];
    }
    
    //set the content size of the scroll view, we keep the height same so it will only
    //scroll horizontally
    self.myScrollView.contentSize = CGSizeMake(self.view.frame.size.width * numberOfViews,
                                               self.view.frame.size.height);
    
    //we set the origin to the 3rd page
    CGPoint scrollPoint = CGPointMake(self.view.frame.size.width * 2, 0);
    //change the scroll view offset the the 3rd page so it will start from there
    [myScrollView setContentOffset:scrollPoint animated:YES];
    
    [self.view addSubview:self.myScrollView];
    
}

//scrolling ends
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
 
    //find the page number you are on
    CGFloat pageWidth = scrollView.frame.size.width;
    int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    NSLog(@"Scrolling - You are now on page %i",page);
}

//dragging ends, please switch off paging to listen for this event
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView
            withVelocity:(CGPoint)velocity
            targetContentOffset:(inout CGPoint *) targetContentOffset
            NS_AVAILABLE_IOS(5_0){
         
    //find the page number you are on
    CGFloat pageWidth = scrollView.frame.size.width;
    int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    NSLog(@"Dragging - You are now on page %i",page);

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Reference

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.