IOS導航欄的使用方法

本文是使用純代碼實現一個導航欄的效果。單擊按鈕並且產生事件。基本思路是:

1.創建一個導航欄(UINavigationBar對象)

2.創建一個導航欄集合(UINavigationItem對象)

3.創建一個左邊按鈕、一個右邊按鈕(UIBarButtonItem對象),並實現對應的事件方法

4.將導航欄集合添加到導航欄中,設置動畫關閉

5.把左右兩個按鈕添加到導航欄集合中去

6.在視圖中顯示當前創建的導航欄

 


具體的實現代碼如下:

ViewController.h文件中的代碼不用改變,如下所示:

  1. #import <UIKit/UIKit.h>  
  2.   
  3. @interface ViewController : UIViewController  
  4.   
  5. @end  

ViewController.m文件中的代碼:

  1. #import "ViewController.h"  
  2.   
  3. @interface ViewController ()  
  4.   
  5. @end  
  6.   
  7. @implementation ViewController  
  8.   
  9. - (void)viewDidLoad  
  10. {  
  11.     [super viewDidLoad];  
  12.     // Do any additional setup after loading the view, typically from a nib.  
  13.       
  14.     //創建一個導航欄  
  15.     UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];  
  16.     //創建一個導航欄集合  
  17.     UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:nil];  
  18.     //在這個集合Item中添加標題,按鈕  
  19.     //style:設置按鈕的風格,一共有三種選擇  
  20.     //action:@selector:設置按鈕的點擊事件  
  21.     //創建一個左邊按鈕  
  22.     UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"左邊" style:UIBarButtonItemStyleBordered target:self action:@selector(clickLeftButton)];  
  23.     //創建一個右邊按鈕  
  24.     UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"右邊" style:UIBarButtonItemStyleDone target:self action:@selector(clickRightButton)];  
  25.       
  26.     //設置導航欄的內容  
  27.     [navItem setTitle:@"凌凌漆"];  
  28.       
  29.     //把導航欄集合添加到導航欄中,設置動畫關閉  
  30.     [navBar pushNavigationItem:navItem animated:NO];  
  31.       
  32.     //把左右兩個按鈕添加到導航欄集合中去  
  33.     [navItem setLeftBarButtonItem:leftButton];  
  34.     [navItem setRightBarButtonItem:rightButton];  
  35.       
  36.     //將標題欄中的內容全部添加到主視圖當中  
  37.     [self.view addSubview:navBar];  
  38.       
  39.     //最後將控件在內存中釋放掉,以避免內存泄露  
  40.     [navItem release];  
  41.     [leftButton release];  
  42.     [rightButton release];  
  43. }  
  44.   
  45. -(void)showDialog:(NSString *)str  
  46. {  
  47.     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"這是一個對話框" message:str delegate:self cancelButtonTitle:@"確定" otherButtonTitles: nil];  
  48.     [alert show];  
  49.     [alert release];  
  50. }  
  51.   
  52. -(void) clickLeftButton  
  53. {  
  54.     [self showDialog:@"點擊了導航欄左邊按鈕"];  
  55. }  
  56.   
  57. -(void) clickRightButton  
  58. {  
  59.     [self showDialog:@"點擊了導航欄右邊按鈕"];  
  60. }  
  61.   
  62. - (void)viewDidUnload  
  63. {  
  64.     [super viewDidUnload];  
  65.     // Release any retained subviews of the main view.  
  66. }  
  67.   
  68. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation  
  69. {  
  70.     return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);  
  71. }  
  72.   
  73. @end  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章