How to add a page indicator inside the navigation bar?

后端 未结 2 1510
北荒
北荒 2020-12-23 15:23

Like twitter did:

\"enter

I have a PageViewController inside a UITabBarControl

2条回答
  •  抹茶落季
    2020-12-23 15:39

    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 () 
    @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 View Second view

提交回复
热议问题