Site icon codewithshabib

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 🙂