UINavigationController 是 iOS 中用于管理视图控制器层次结构的一个重要组件,通常用于实现基于堆栈的导航。它提供了一种用户界面,允许用户在视图控制器之间进行层次化的导航,例如从列表视图到详细视图。

UINavigationController 的主要功能

  1. 管理视图控制器堆栈:使用一个堆栈数据结构来管理视图控制器。堆栈的顶端是当前显示的视图控制器。
  2. 导航栏:在屏幕顶部显示一个导航栏,通常包含返回按钮(左端)、标题(中间)和其他控制项(右方)。

  1. 导航动画:提供标准的推入(push)和弹出(pop)动画,增强用户的导航体验。

如何使用 UINavigationController

初始化和基本使用

// 在AppDelegate.m中
#import "AppDelegate.h"
#import "RootViewController.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    RootViewController *rootVC = [[RootViewController alloc] init];
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:rootVC];
    
    self.window.rootViewController = navController;
    [self.window makeKeyAndVisible];
    
    return YES;
}

@end

管理视图控制器堆栈

推入视图控制器

使用 pushViewController:animated: 方法将一个视图控制器推入导航堆栈,并显示它。

UIViewController *newVC = [[UIViewController alloc] init];
newVC.view.backgroundColor = [UIColor whiteColor];
[self.navigationController pushViewController:newVC animated:YES];

弹出视图控制器

使用 popViewControllerAnimated: 方法将当前视图控制器从堆栈中移除,并返回到前一个视图控制器。

[self.navigationController popViewControllerAnimated:YES];

自定义导航栏

设置导航栏标题

可以在视图控制器中设置导航栏的标题。

self.title = @"Home";

自定义导航栏按钮

可以在视图控制器中添加自定义的导航栏按钮。

UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Right" style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonTapped)];
self.navigationItem.rightBarButtonItem = rightButton;

实现按钮的动作:

- (void)rightButtonTapped {
    NSLog(@"Right button tapped");
}

导航栏样式定制

可以通过 UINavigationBar 的属性来自定义导航栏的样式。

设置导航栏颜色

self.navigationController.navigationBar.barTintColor = [UIColor blueColor];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor]; // 设置返回按钮和其他按钮的颜色
self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor whiteColor]}; // 设置标题颜色

设置透明导航栏

[self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
self.navigationController.navigationBar.shadowImage = [UIImage new];
self.navigationController.navigationBar.translucent = YES;

处理导航控制器中的返回动作

可以通过实现 UINavigationControllerDelegate 协议来处理导航控制器中的返回动作。

示例:拦截返回按钮动作

@interface MyViewController () <UINavigationControllerDelegate>
@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.delegate = self;
}

// 实现代理方法
- (BOOL)navigationController:(UINavigationController *)navigationController shouldPopItem:(UINavigationItem *)item {
    // 在这里处理返回按钮的动作
    // 返回 YES 表示允许返回,返回 NO 表示阻止返回
    return YES;
}

@end