Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a page indicator inside the navigation bar?

Tags:

ios

Like twitter did:

enter image description here

I have a PageViewController inside a UITabBarController which in turn is inside a UINavigationController.

Could anyone tell me how to show the page indicator inside the navigation bar?

like image 201
HanXu Avatar asked Jan 12 '14 11:01

HanXu


1 Answers

Edit: I just figured out that navigationController.viewControllers only contains the stack. I will post an edit in a minute

Edit 2: Well, it seems that you have to know the number of view controllers before hand.

Maybe not the best solution, but it works for me. Just tried :)

@interface ViewController () <UINavigationControllerDelegate>
@property (nonatomic, strong) UIPageControl *pageControl;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    UINavigationController *navController = self.navigationController;
    navController.delegate = self;

    navController.navigationBar.barTintColor = [UIColor colorWithRed:.2
                                                               green:.4
                                                                blue:.9
                                                               alpha:1];

    CGSize navBarSize = navController.navigationBar.bounds.size;
    CGPoint origin = CGPointMake( navBarSize.width/2, navBarSize.height/2 );

    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(origin.x, origin.y,
                                                                       0, 0)];

    //Or whatever number of viewcontrollers you have
    [self.pageControl setNumberOfPages:2];

    [navController.navigationBar addSubview:self.pageControl];

    navController.delegate = self;
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    int index = [navigationController.viewControllers indexOfObject:viewController];
    self.pageControl.currentPage = index;
}

@end

Here are some screenshots.

First ViewSecond view

like image 196
chrs Avatar answered Nov 09 '22 21:11

chrs