UINavigationController 學習摘要

UINavigationController學習摘要

UINavigagtionController負責管理多個UIViewController之間的水平方向的push(壓入)和pop(彈出),並同步修改它一個子視圖:navigationBar,即,我們常說的導航條。

我們可以看一下它的結構圖,從結構圖中,我們看到,它有一個NSArray的數據成員,即它管理的視圖棧。




UINavigationController 是繼承自UIViewController 的子類,也有自己的視圖,它至少有3個子視圖:navigationBar、topViewController以及toolBar。我們首先看一下蘋果幫助文檔中的結構圖:

 

下面我們重點講一下navigationBar和toolBar的工作原理

1、navigationBar

它位於整個視圖的頂部。講到它,我們先查一下UIViewController對象中一個navigationTtem 屬性,類型爲 UINavigationItem,它和UINavigationBar 不同,UINavigationItem 不是UIView 子類,不能在屏幕上 顯示,主要是爲 UINavigationBar 對象提供繪圖所需的內容。當某一個UIViewController 對象爲 UINavigationController 的棧頂對象時,UINavigationBar 對象會使用UIViewController 對象中 navigationItem 並設置相應的屬性。

UINavigationBar和UINavigationItem這兩者之間的關係圖:

UINavigationItem 包括 4 個部分的可以自定義的部分:leftBarButtonItem、rightBarButtonItem
、backBarButtonItem以及titleView。他們都是指針,前三者都指向UIBarButtonItem  實例(此類按鈕只能在UINavigationBar 或 UIToolBar 上顯示)也不是UIView 子類,只提供 UINavigationBar 繪圖所需的內容。

其中 backBarButtonItem 自定義比較的特殊:研讀 UINavigationControllerClass Reference 中,在“Updating the Navigation Bar” 小節,有這麼一段話:

The bar button item on the left sideof the navigation bar allows for navigation back to the previous viewcontroller on the navigation stack. The navigationcontroller updates the leftside of the navigation bar as follows:

If the new top-level viewcontroller has a custom left bar button item, that item is displayed. Tospecify a custom left bar button item, set the leftBarButtonItem property ofthe view controller’s navigation item.

If the top-level view controllerdoes not have a custom left bar button item, butthe navigation item of thepreviousview controllerhas a valid item in its backBarButtonItem property,the navigation bar displays that item.

If a custom bar button item is notspecified by either of the view controllers, a default back button is used andits title is set to the value of the title property of the previous viewcontroller— that is, the view controller one level down on the stack. (If thereis only one view controller on the navigation stack, no back button isdisplayed.)

從上面的官方解釋來看,使用 pushViewController 切換到下一個視圖時,navigation controller 按照以下3 條順序更改導航欄的左側按鈕:

1)、如果 B 視圖有一個自定義的左側按鈕(leftBarButtonItem),則會顯示這個 自定義按鈕;

2)、如果 B 沒有自定義按鈕,但是 A 視圖的 backBarButtonItem 屬性有自定義項, 則顯示這個自定義項;

3)、如果前 2 條都沒有,則默認顯示一個後退按鈕,後退按鈕的標題是A 視圖的標題。

從第二點來看,我們可以在A視圖中自定義back按鈕,示例代碼如下:

UIBarButtonItem *backItem = [[UIBarButtonItemalloc]

initWithTitle:@"返回"style:UIBarButtonItemStyleBordered

target:nil action:nil];

[self.navigationItem setBackBarButtonItem:backItem];

[backItem release];

經過測試驗證,指定事件並也不會起作用,需要繼續研究,後期可以補充。

2、toolBar

與navigationBar類似,在UIViewController對象中也有一個toolBarItems的屬性,用於定義toolBar上顯示的內容,我們可以看下面的結構圖:

值得注意的是,默認情況下是不顯示toolBar的,需要調用UINavigationController對象的的-(void)setToolbarHidden:(BOOL)hiddenanimated:(BOOL)animated

方法來顯示和隱藏toolBar。一般是採用設置UIViewController的hidesBottomBarWhenPushed的值爲YES,當push或者pop時,自動隱藏底部的toolBar。

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章