SHViewPager: Custom Controller for iOS

Hello everybody,

For a recent project of mine, I had created this custom controller. This is quite similar to the ViewPager control used in Android. I’ve named this controller SHViewPager, here is the gitHub link.

This controller uses a datasource and a delegate protocol. You’ve to implement at least three datasource protocols (that are required) to avoid exceptions. These methods are:

– The first one

// total number of pages to be displayed by the controller
-(NSInteger)numberOfPagesInViewPager:(SHViewPager*)viewPager;

Example:

-(NSInteger)numberOfPagesInViewPager:(SHViewPager*)viewPager
{
    // 5 pages to be displayed by the controller
    return 5;
}

– The second one

// the viewcontroller that will contain the pages, in most of the cases it will be the same viewcontroller that is acting as the datasource and delegate
// i.e. return value will be 'self'
- (UIViewController *)containerControllerForViewPager:(SHViewPager *)viewPager;

Example:

- (UIViewController *)containerControllerForViewPager:(SHViewPager *)viewPager
{
    return self;
}

– The third one

// the viewcontroller that is to be shown as as a page in the pager
- (UIViewController *)viewPager:(SHViewPager *)viewPager controllerForPageAtIndex:(NSInteger)index;

Example:

- (UIViewController *)viewPager:(SHViewPager *)viewPager controllerForPageAtIndex:(NSInteger)index
{
    UIViewController *viewController = [[UIViewController alloc] initWithNibName:@"UIViewController" bundle:nil];
    return viewController;
}

To display the contents, you need to call the instance method reloadData in your desired method block, typically in viewDidLoad.
Example:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // your code
    [viewPager reloadData];
}

This custom controller is under MIT licence. Feel free to use and contribute 🙂

This Post Has 2 Comments

  1. Asif Rana

    Hey the view pager is not showing the full contents of the view controller at index, means there is no vertical scrolling to show the full contents. Can I modify it to use Custom Views instead of UIVIewController for every page index?

  2. Houssam Hammoud

    hi why when I go to the details and I need to go back to the view pager the content will be returned to the first index ?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.