ios開發之自訂預設產生的導覽列 標題 顏色 返回按鈕

來源:互聯網
上載者:User

ios開發之自訂預設產生的導覽列 標題 顏色 返回按鈕

一 修改導覽列顏色 導覽列在哪個頁面代碼放在那裡面

self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:(21.0/255.0) green:(153.0 / 255.0) blue:(224.0 / 255.0) alpha:1]; //定義導覽列顏色

self.navigationItem.title = @自訂; //定義導覽列的標題

二 導覽列內建一個返回按鈕,我們需要定製它的樣式,這可以有許多辦法。比如 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:[UIImage imageNamed:@返回.png] forState:UIControlStateNormal];

[btn addTarget:selfaction:@selector(goBackAction)forControlEvents:UIControlEventTouchUpInside];

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


3、把BarButtonItem 設定為 navigationItem的leftBarButton。


//設定導覽列的leftButton

self.navigationItem.leftBarButtonItem=back;


4、編寫Button的事件代碼。

-(void)goBackAction{

// 在這裡增加返回按鈕的自訂動作

[self.navigationControllerpopViewControllerAnimated:YES];

}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.