zfe8da
Last Updated: February 25, 2016
·
35.03K
· anthonylevings
Speechrocket4 square

How to get a UIScrollView scrolling and paging (Xcode for 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 the view 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:

// 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).

The original post can be found here: http://sketchytech.blogspot.com/2012/04/unlocking-magic-of-uiscrollview.html

Say Thanks
Respond