来源:雨松MOMO
利用代码在屏幕中添加一个标题栏,并且在标题栏左右两方在添加两个按钮,点击后响应这两个按钮。
这里设置标题栏的显示范围。
2 | UINavigationBar *navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; |
有了标题栏后,须要在标题栏上添加一个集合Item用来放置 标题内容,按钮等。
2 | UINavigationItem *navigationItem = [[UINavigationItem alloc] initWithTitle:nil]; |
在这个集合Item中添加标题,按钮。
style:设置按钮的风格,一共有3中选择。
action:@selector:设置按钮点击事件。
02 | UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@ "左边" |
03 | style:UIBarButtonItemStyleBordered |
05 | action:@selector(clickLeftButton)]; |
08 | UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@ "右边" |
09 | style:UIBarButtonItemStyleDone |
11 | action:@selector(clickRightButton)]; |
13 | [navigationItem setTitle:@ "雨松MOMO程序世界" ]; |
将标题栏中的内容全部添加到主视图当中。
2 | [self.view addSubview:navigationBar]; |
最后将控件在内存中释放掉,避免内存泄漏。
2 | [navigationItem release]; |
如图所示:添加这两个按钮的点击响应事件。
01 | -( void )clickLeftButton |
04 | [self showDialog:@ "点击了导航栏左边按钮" ]; |
08 | -( void )clickRightButton |
11 | [self showDialog:@ "点击了导航栏右边按钮" ]; |
点击后打开一个Dialog对话框,根据点击不同的按钮传入不同的显示内容。
1 | -( void )showDialog:(NSString *) str |
4 | UIAlertView * alert= [[UIAlertView alloc] initWithTitle:@ "这是一个对话框" message:str delegate:self cancelButtonTitle:@ "确定" otherButtonTitles: nil]; |
最后贴上完整的代码
01 | #import "TitleViewController.h" |
03 | @implementation TitleViewController |
05 | - ( void )didReceiveMemoryWarning |
08 | [super didReceiveMemoryWarning]; |
13 | #pragma mark - View lifecycle |
21 | UINavigationBar *navigationBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; |
24 | UINavigationItem *navigationItem = [[UINavigationItem alloc] initWithTitle:nil]; |
27 | UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@ "左边" |
28 | style:UIBarButtonItemStyleBordered |
30 | action:@selector(clickLeftButton)]; |
33 | UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@ "右边" |
34 | style:UIBarButtonItemStyleDone |
36 | action:@selector(clickRightButton)]; |
38 | [navigationItem setTitle:@ "雨松MOMO程序世界" ]; |
41 | [navigationBar pushNavigationItem:navigationItem animated:NO]; |
44 | [navigationItem setLeftBarButtonItem:leftButton]; |
45 | [navigationItem setRightBarButtonItem:rightButton]; |
48 | [self.view addSubview:navigationBar]; |
51 | [navigationItem release]; |
53 | [rightButton release]; |
57 | -( void )clickLeftButton |
60 | [self showDialog:@ "点击了导航栏左边按钮" ]; |
64 | -( void )clickRightButton |
67 | [self showDialog:@ "点击了导航栏右边按钮" ]; |
71 | -( void )showDialog:(NSString *) str |
74 | UIAlertView * alert= [[UIAlertView alloc] initWithTitle:@ "这是一个对话框" message:str delegate:self cancelButtonTitle:@ "确定" otherButtonTitles: nil]; |
82 | [super viewDidUnload]; |
87 | - ( BOOL )shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation |
90 | return (interfaceOrientation == UIInterfaceOrientationPortrait); |