How do I use UIPageControl in my app?

ZenthyxProgramming picture ZenthyxProgramming · Oct 19, 2013 · Viewed 30.2k times · Source

I am making an app where I need some images can be scrolled through using a UIPageControl. Sadly, I don't know how to use a UIPageControl, or a UIScrollView either. A link to a YouTube video or Xcode documentation by Apple would be much appreciated!

Thanks in advance!!

Answer

Rocker picture Rocker · Oct 19, 2013

here is a code which will help you

 CGSize size = [[UIScreen mainScreen] bounds].size;
 CGFloat frameX = size.width;
 CGFloat frameY = size.height-30; //padding for UIpageControl

 UIScrollView  *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(offsetX, offsetY, frameX, frameY)];
 scrollView.pagingEnabled = YES;

scrollView.backgroundColor = [UIColor clearColor];
scrollView.contentSize = CGSizeMake(frameX, frameY);


[self.view addSubview: scrollView];

// let say you have array of image in imageArray

for(int i = 0; i < [imageArray]; i++)
{
   UIImage *image = [UIImage imageNamed:[imageArray objectAtIndex:i]];
   imageView = [[UIImageView alloc] initWithImage:image];
   imageView.frame = CGRectMake(frameX * i, 0.0, frameX, frameY);
   [scrollView addSubview:imageView];
}

scrollView.contentSize = CGSizeMake(frameX*[imageArray count], frameY); 

please declare the variables according to scope of use. i have declared all the variables locally so that might not get confuse and also add the UIPageControl at the bottom of your viewcontroller

Implement the delegate method of UIScrollView to the current Page indicator

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
  {
     float width = scrollView.frame.size.width;
     float xPos = scrollView.contentOffset.x+10;

     //Calculate the page we are on based on x coordinate position and width of scroll view
     pageControl.currentPage = (int)xPos/width;   
  }

where pageControl is UIPageControl added on bottom your viewcontroller