檢視控制器UINavigationController的介紹與基本使用

机械心發表於2024-06-30

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

相關文章