定製導航欄的返回按鈕

導航欄自帶一個返回按鈕,我們需要定製它的樣式,這可以有許多辦法。比如 Hack 導航欄的視圖層次。如果你不想 Hack 導航欄,那麼你可以使用NavigationBarDelegate。問題在於,如果是導航控制器自帶的NavigationBar,你將不能訪問NavigationBar(程序會Crash)。這是蘋果文檔中的說明:

Note that if you use aUINavigationController object to manage hierarchical navigation, you should notdirectly access the navigation bar object.

這裏,我們提供另一種“定製”方法。也許不能稱之爲定製,因爲我們實際上是將默認的返回按鈕隱藏了,並提供一個自定義的返回按鈕作爲導航欄的leftButton。使用這種方法,我們不僅可以定製按鈕的樣式(標題和背景圖片),而且可以觸發自定義的方法。默認的返回按鈕動作是popViewController,我們可以修改爲其他動作。

這個過程大概分爲4個步驟:

1、隱藏默認返回按鈕,這是通過設置navigationItem的hidesBackButton爲YES做到的:

// 隱藏默認的"返回"按鈕

[self.navigationItemsetHidesBackButton:YES];

 

2、自定義一個BarButtonItem。首先,我們定製一個UIButton。 這個UIButton用buttonWithType:UIButtonTypeCustom方法初始化。然後用setBarckgroundImage方法定製按鈕的背景圖片,用addTarget方法指定按鈕的事件處理方法。這樣我們就獲得了一個完全定製的Button。BarButtonItem有一個initWithCustomView:的初始化方法。我們可以把一個定製的視圖(比如我們定製的Button)作爲這個方法的參數,構建出一個BarButtonItem。

 

// 自定義導航欄的"返回"按鈕

    UIButton *btn = [UIButtonbuttonWithType:UIButtonTypeCustom];

btn.frame = CGRectMake(15, 5, 38, 38);

[btn setBackgroundImage:[UIImageimageNamed:@"按鈕-返回1.png"] forState:UIControlStateNormal];

[btn addTargetselfaction@selector(goBackAction) forControlEventsUIControlEventTouchUpInside];

    UIBarButtonItem*back=[[UIBarButtonItemalloc]initWithCustomView:btn];

 

3、把BarButtonItem 設置爲 navigationItem的leftBarButton。

 

// 設置導航欄的leftButton

self.navigationItem.leftBarButtonItem=back;

   

4、編寫Button的事件代碼。

-(void)goBackAction{

// 在這裏增加返回按鈕的自定義動作

[self.navigationControllerpopViewControllerAnimated:YES];

}

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