本文是使用純代碼實現一個導航欄的效果。單擊按鈕並且產生事件。基本思路是:
1.創建一個導航欄(UINavigationBar對象)
2.創建一個導航欄集合(UINavigationItem對象)
3.創建一個左邊按鈕、一個右邊按鈕(UIBarButtonItem對象),並實現對應的事件方法
4.將導航欄集合添加到導航欄中,設置動畫關閉
5.把左右兩個按鈕添加到導航欄集合中去
6.在視圖中顯示當前創建的導航欄
具體的實現代碼如下:
ViewController.h文件中的代碼不用改變,如下所示:
- #import <UIKit/UIKit.h>
- @interface ViewController : UIViewController
- @end
ViewController.m文件中的代碼:
- #import "ViewController.h"
- @interface ViewController ()
- @end
- @implementation ViewController
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view, typically from a nib.
- //創建一個導航欄
- UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
- //創建一個導航欄集合
- UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle:nil];
- //在這個集合Item中添加標題,按鈕
- //style:設置按鈕的風格,一共有三種選擇
- //action:@selector:設置按鈕的點擊事件
- //創建一個左邊按鈕
- UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"左邊" style:UIBarButtonItemStyleBordered target:self action:@selector(clickLeftButton)];
- //創建一個右邊按鈕
- UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"右邊" style:UIBarButtonItemStyleDone target:self action:@selector(clickRightButton)];
- //設置導航欄的內容
- [navItem setTitle:@"凌凌漆"];
- //把導航欄集合添加到導航欄中,設置動畫關閉
- [navBar pushNavigationItem:navItem animated:NO];
- //把左右兩個按鈕添加到導航欄集合中去
- [navItem setLeftBarButtonItem:leftButton];
- [navItem setRightBarButtonItem:rightButton];
- //將標題欄中的內容全部添加到主視圖當中
- [self.view addSubview:navBar];
- //最後將控件在內存中釋放掉,以避免內存泄露
- [navItem release];
- [leftButton release];
- [rightButton release];
- }
- -(void)showDialog:(NSString *)str
- {
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"這是一個對話框" message:str delegate:self cancelButtonTitle:@"確定" otherButtonTitles: nil];
- [alert show];
- [alert release];
- }
- -(void) clickLeftButton
- {
- [self showDialog:@"點擊了導航欄左邊按鈕"];
- }
- -(void) clickRightButton
- {
- [self showDialog:@"點擊了導航欄右邊按鈕"];
- }
- - (void)viewDidUnload
- {
- [super viewDidUnload];
- // Release any retained subviews of the main view.
- }
- - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
- {
- return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
- }
- @end