Thursday, January 10, 2013

Page Control for Switching Between Views

This is a tutorial request from Ze Kitez.

As much as possible, I tried to do everything in Interface Builder, but sadly, some of the logic could not be done in IB.

1. Create a New Xcode Project, choose Single View Application template.


A ViewController will be created for us.

I'm using the latest Xcode up to date, so you may see a longer UIView in our xib file (for iPhone 5 devices). But if you want the old UIView size, you may change it by choosing Retina 3.5 Full Screen on the Simulated Metrics (right panel of the image above).

2. Search for a ScrollView object from the Objects Library (Lower-Right panel) and drag the ScrollView to the UIView (the gray rectangle above).
Leave a small space below the scrollView so that we can put the PageControl on that area.

3. Search for a PageControl object from the Objects Library (Lower-Right panel) and drag it just below our scrollView.

4. Add a <UIScrollViewDelegate> on your Interface header.
//You may put it in your .h file
@interface ViewController : UIViewController <UIScrollViewDelegate>
//OR in your .m file, directly above the @implementation header
@interface ViewController ( ) <UIScrollViewDelegate>

Read about Interface And Implementation topic to know the difference of the two.

5. Add an IBOutlet property for scrollView and pageControl in your interface.
@property (nonatomic, strong) IBOutlet UIScrollView *scrollView;
@property (nonatomicstrongIBOutlet UIPageControl *pageControl;

And, synthesize these properties in your implementation section.
@synthesize scrollView;
@synthesize pageControl;


6. Connect your IBOutlet properties to the objects in your .xib file.

7. Right-click on your scrollView object in your .xib file. Set the delegate to the File's Owner.

8. Click the scrollView object in your .xib file and only check the Scrolling Enabled and Paging Enabled.

9. Click the pageControl object in your .xib file.
  • Set the number of Pages you want. Number of Pages == number of PageControl dots
  • Change TintColor according to your preference. 
    • Tint Color is for the normal color of the pageControl dots
    • Current Page is for the currently selected page


The rest of the tutorial will be done programmatically.

//In this tutorial, I added three images to my project, namely, image1, image2, image3.



10. Add an NSArray property to your interface (.h) and synthesize your array to your implementation (.m) file.
@property (nonatomicstrong) NSArray *imageArray; //.h
@synthesize imageArray; //.m


11. In your viewDidLoad, add these codes.
- (void)viewDidLoad
{
    [super viewDidLoad];
//Put the names of our image files in our array.
    imageArray = [[NSArray alloc] initWithObjects:@"image1.jpg", @"image2.jpg", @"image3.jpg", nil];
    
    for (int i = 0; i < [imageArray count]; i++) {
//We'll create an imageView object in every 'page' of our scrollView.
        CGRect frame;
        frame.origin.x = self.scrollView.frame.size.width * i;
        frame.origin.y = 0;
        frame.sizeself.scrollView.frame.size;
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
        imageView.image = [UIImage imageNamed:[imageArray objectAtIndex:i]];
        [self.scrollView addSubview:imageView];
    }
//Set the content size of our scrollview according to the total width of our imageView objects.
    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * [imageArray count], scrollView.frame.size.height);
}

11. Implement the scrollViewDidScroll method of ScrollViewDelegate.

#pragma mark - UIScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)sender
{
    // Update the page when more than 50% of the previous/next page is visible
    CGFloat pageWidth = self.scrollView.frame.size.width;
    int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    self.pageControl.currentPage = page;
}

12. Hit Run and you're done!








39 comments:

  1. Very useful, you helped me a lot, thank you so much- got a question though:
    using the same tutorial, how should i go about sharing images on social media (facebook for example)?

    Your help is highly appreciated.

    ReplyDelete
    Replies
    1. You need to study and learn their SDK.. https://developers.facebook.com/docs/tutorials/ios-sdk-tutorial/ :)

      Delete
    2. Hi again,

      Thank you for your quick reply.

      i am familiar with integrating social media services onto given ios app which i did onto your tutorial.
      I added an action button, once pressed it open fb sharing interface however i can't seem to attach a specific image to FB request (image 1 for example and so on).

      Just wondering if you can assist on this one.

      thnx

      Delete
    3. Sorry, I don't think I'll be able to tackle integration of FB API. I actually have not been able to post tutorials for how many months already. I have been busy. :)

      Delete
  2. Hi Ziyad,
    This is vivek i can help you on this.Please mail me if you need further help.
    My Mail Id is: dricoode@gmail.com

    ReplyDelete
    Replies
    1. Hi Vivek,

      I guess what i need is very simple but been knocking my head around it a bit.

      Using Jenn's tutorial, i just need to add a Facebook Share function where by user can share any of the given images.

      Highly appreciate your help.

      Delete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Hi, thanks for your tutorial very much.

    I faced a problem when I test your tutorial on my iPod5 (iOS6).

    The problem is, the size of scroll view is always 0.

    And I solved this problem by change the initialization of scroll view to "viewDidAppear".

    It seems that the IBOutlet haven't been set up in "viewDidLoad".

    ReplyDelete
    Replies
    1. Hi Wani,

      This is vivek, unfortunately you are thinking wrong, all the IBOutlets use to set in "viewDidLoad", this is the best method to initialize the IBOutlets.

      Delete
  5. thanks for your tutorial, I has a question, when I use storyboard, the page control cannot work, when I use xib, just like your tutorial, it works well, I want to know why storyboard can't, hope your reply, thanks.

    ReplyDelete
  6. Great tutorial Jenn.
    Would you mind moving to a better Blogger? Something which has a sensible font and code inboxing/highlighting? Something like Jekyll

    ReplyDelete
  7. Thanks for the tutorial! Got me implementing UIScrollView in no time =D

    ReplyDelete
  8. Thanks for a nice tutorial especially the screen snapshot which is very helpful.

    ReplyDelete
  9. Four comments up, it was mentioned that this did not work in a storyboard, but I did mine exactly the way the tutorial explained in a storyboard and it worked perfectly. THANK YOU!

    ReplyDelete
    Replies
    1. the way explained, it don't worked. Have to move all contents from viewDidLoad to viewDidAppear.

      Delete
  10. great tutorial, I love you babe

    ReplyDelete
  11. All works good ONLY WHEN I move all viewDidLoad content to viewDidAppear.

    ReplyDelete
  12. I like the way you write tutorials. Thanks for taking the time to do it ;)

    ReplyDelete
  13. Great article!

    However, there were some parts I think you should add:
    1) When creating a project, uncheck StoryBoard Checkbox
    2) Since I am new to XCode, the word "Interface" was confusing. I figured it out. You were implying something like ViewController.*
    3) You should have link with all the source code and project files

    Other than that, Great Job!!!

    ReplyDelete
  14. hey thank you so much
    can you plz tell me how can i make it vertically scrollable.

    ReplyDelete
  15. thanks works great can you tell me how to do it from right to left

    ReplyDelete
  16. Thanks for your clear and nice tutorial, and I have one question here, if I want to click on page controller buttons the image should be change, like say suppose I have 3 images if I clicked on 3 page button on page controller the scroll view should jump to 3rd image. any help??

    ReplyDelete
  17. I thank you, thank you, thank you!!!!!

    ReplyDelete
  18. Hi Jenn, very fine tutorial. I am now modifying this into something like this ----> http://stackoverflow.com/questions/19185446/horizontal-uiscrollview-inside-custom-uitableviewcell-using-ib-storyboard-no
    Your tutorial helped me a lot. Thanks.

    ReplyDelete
  19. Very nice tutorial, with its help I was able to build a paged control in no time! Keep up the good work! Cheers, Janos

    ReplyDelete
  20. Hi,

    I have a question, I have managed to control and Page ScrollView but I have a few questions to advance my project:
    - How to add a button to a page scroll View?
    - How to give a action buttons on the ScrollView, but the action must be on the pages of the scroll View?
    - How do I delete an image when the index goes to 1 ScrollView index [1];
    - Can we sailed from button on a Scroll View?

    Regards,
    Bilel

    ReplyDelete
  21. Thank you, helped a lot !.......
    Nice tutorial...............

    ReplyDelete