您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 導航視圖控制器實戰:堆疊跳轉、導覽列客製與頁面傳值

編輯:iOS 開發綜合

先搞懂那 64 像素從哪來

在 iOS 中,UINavigationController 管理的每一頁都是一個 UIViewController,頁面之間以「堆疊」的關係串起來。導覽列本身高度是 44pt,狀態列 20pt,兩者相加正好 64pt。只要把 navigationBar 的 translucent 屬性設為 NO,控制器的 view 原點就會自動從導覽列下方開始計算,避免你辛苦排好的子視圖被半透明的導覽列蓋住。

 self.navigationController.navigationBar.translucent = NO;

導覽列的標題、titleView 與左右按鈕

很多人會直接把文字寫在 navigationController.navigationBar 上,但正確做法應該是操作「當前的 navigationItem」,因為每一頁都有自己的導覽列內容。除了單純的文字標題,還可以用 titleView 換成 UISegmentedControl 這類自訂控件;左右兩側則透過 leftBarButtonItem 與 rightBarButtonItem 擺放系統樣式按鈕或自訂 view。

 self.navigationItem.title = @"鷹王電影";

UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:@[@"信息", @"通話"]];
self.navigationItem.titleView = seg;

self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]
    initWithBarButtonSystemItem:UIBarButtonSystemItemDone
    target:self action:@selector(leftButtonAction:)];

UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
rightButton.frame = CGRectMake(0, 0, 40, 40);
[rightButton setImage:[UIImage imageNamed:@"天平.png"] forState:UIControlStateNormal];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];

注意 barTintColor 決定的是導覽列的底色,跟 view 的 backgroundColor 是兩回事,不要把概念混在一起。

push 與 pop:三個必學方法

導航控制器的跳轉全靠 UINavigationController 的堆疊操作。pushViewController:animated: 把新頁面壓入堆疊;popViewControllerAnimated: 回到上一頁;popToRootViewControllerAnimated: 則一次跳回堆疊最底層。若只是想暫時覆蓋顯示,也可以改用 presentViewController 的模態方式,兩者的使用時機取決於「使用者是否需要沿路返回」。

 SecondViewController *secVC = [[SecondViewController alloc] init];
[self.navigationController pushViewController:secVC animated:YES];
[secVC release];

// 回到上一頁
// [self.navigationController popViewControllerAnimated:YES];

// 直接回到根控制器
// [self.navigationController popToRootViewControllerAnimated:YES];

頁面之間怎麼傳值

最直覺的方式是「屬性傳值」:在目標控制器宣告好屬性,push 之前把值塞進去。字串建議用 copy,物件用 retain,整數用 assign,並在 dealloc 中相應釋放,這在 MRC 年代尤其關鍵。

 // SecondViewController.h
@property (nonatomic, assign) NSInteger number;
@property (nonatomic, copy) NSString *str;
@property (nonatomic, retain) NSArray *arr;

// 跳轉前賦值
secVC.number = 100;
secVC.str = self.textfield.text;
secVC.arr = @[@"楊林", @"劉山山"];

反方向的回傳(第二頁把資料送回第一頁)則需要 delegate 或 block,這部分在「界面傳值」的章節會再詳細拆解。

整套機制的重點其實只有一句話:導航控制器負責「怎麼去」,navigationItem 負責「長什麼樣」,而資料則由控制器自己負責帶過去。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved