标签:
UINaviGationController通常被我们称为导航栏,他是视图与视图之间联系沟通的桥梁,一些著名的app都用到了他。下面我们来看一下如何建立一个navigation。
首先,我们通常新建工程是直接将视图控制器添加到window上,而现在有navigation以后,就多了一层:
Appdelegete.h:
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- {
- self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
-
- self.window.backgroundColor = [UIColor whiteColor];
- RootViewController *root = [[RootViewController alloc]init];
- UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:root];
- [_window setRootViewController:nav];
-
- [nav release];
- [root release];
-
- [self.window makeKeyAndVisible];
- return YES;
- }
这样我们的navigation就加载上去了。下面我们来设置navigation的属性:
- - (void)viewDidLoad
- {
- [super viewDidLoad];
-
- [self.navigationController.navigationBar setTranslucent:NO];
- self.title = @"navigationcontroller";
- [self.navigationController.navigationBar setBarTintColor:[UIColor purpleColor]];
- self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonItemStyleDone target:self action:Nil];
- self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonItemStylePlain target:self action:Nil];
- [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
- }
效果图如下:
这里还有一个属性常用,就是:
- NSArray *arr = [NSArray arrayWithObjects:@"1",@"2", nil nil];
- UISegmentedControl *segment = [[UISegmentedControl alloc]initWithItems:arr];
- self.navigationItem.titleView = segment;
效果如下:
对,我们看到中间的字变成了两个可选的按钮,这就是navigation的另一个属性:navigationitem.titleview。
下面我们再建立一个视图,看一下两个视图之前是怎样通信的。
在第二个视图中,我添加了一个button来显示,并加了一个成员变量来接收从第一个视图中穿过来的值:
- @interface SecondViewController : UIViewController
- @property (copy,nonatomic) NSString *str;
- @end
- - (void)viewDidLoad
- {
- [super viewDidLoad];
-
- self.title = @"second";
- UIButton *aBUTTON = [[UIButton alloc]initWithFrame:CGRectMake(30, 30, 50, 30)];
- [aBUTTON setTitle:_str forState:UIControlStateNormal];
- [aBUTTON addTarget:self action:@selector(clicked) forControlEvents:UIControlEventTouchUpInside];
- [self.view addSubview:aBUTTON];
- }
然后我将第一个视图的右边按钮添加一个事件,点击按钮,就会推出第二个视图,并显示我们传过来的值:
- - (void)clicked{
- SecondViewController *second = [[SecondViewController alloc]init];
- [self.navigationController pushViewController:second animated:YES];
- second.str = @"hello!!";
- [second release];
- }
下面,我们来运行一下:
点进按钮以后,我们的第二个视图推出,button显示了传过来的值。
然后我们点击回button,还有navigation另外一个方法:
- - (void)clicked{
- [self.navigationController popViewControllerAnimated:YES];
- }
这样就可以回到第一个视图。
ios UINavigationController
标签:
原文地址:http://www.cnblogs.com/Free-Thinker/p/5011066.html