Unlocking the magic of the UIScrollView (Xcode/iOS)

The secret to understanding the scroll view is that it has a frame size and a content size. You only need to create the frame size big enough to fit on the screen whereas the content size will be larger in order for it to scroll.

Here is code that can be placed in the viewDidLoad of your ViewController.m file, and incorporates paging as well. It assumes that you have already created a UIScrollView in Interface Builder and called it scrollView:


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Adjust scroll view content size, set background colour and turn on paging
    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * 12,  
    scrollView.frame.size.height);
    scrollView.pagingEnabled=YES;
    scrollView.backgroundColor = [UIColor blackColor];

     // Generate content for our scroll view using the frame height and width as the reference
     point
    int i = 0;
    while (i<=11) {
       
        UIView *views = [[UIView alloc]
        initWithFrame:CGRectMake(((scrollView.frame.size.width)*i)+20, 10,
        (scrollView.frame.size.width)-40, scrollView.frame.size.height-20)];
        views.backgroundColor=[UIColor yellowColor];
        [views setTag:i];
        [scrollView addSubview:views];
       
        i++;
    }

}


That's all there is to getting a working sample (but remember to note Apple's warning in their documentation not to incorporate web views and tables in scroll views).

Comments