且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在导航栏中添加页面指示器?

更新时间:2023-12-05 16:41:34

编辑:我只知道navigationController.viewControllers只包含叠加。
我将在一分钟内发布一个编辑

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

编辑2:好吧,看来你必须事先知道视图控制器的数量。

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

以下是一些截图。