我想用pushViewController的方式切换页面,但是却没有成功。究其原因是直接使用了self.navigationController,没有alloc,其值为nil。
要想用导航条功能,需要在AppDelegate中的didFinishLaunchingWithOptions方法里加入以下几行代码:
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController: self.viewController]; [self.window makeKeyAndVisible];
这几行代码把ViewController的实例对象作为根视图,而且viewController是UINavigationController类型的对象。
有了导航条以后,试着设置其中的navigation item。
控制这些navigation item的是UINavigationItem类,它的属性与方法列表如下:
1.backBarButtonItem:
navigationItem中的backBarButtonItem用于返回上一级view,可以为它设定一张图片或者设置title,但不要想着为它设定自定义视图,因为这一导航项会忽略所有添加custom views的操作。官方文档说明:When configuring your bar button item, do not assign a custom view to it; the navigation item ignores custom views in the back bar button anyway.
2.leftBarButtonItem
由于backBarButtonItem的可设置性不高,可以自定义左边按钮来替代。
隐藏掉backBarButtonItem
// But hide the backBarButtonItem.
[self.navigationItem setHidesBackButton: YES];
然后设置leftBarButtonItem
UIButton *BtnView = [[UIButton alloc] initWithFrame: CGRectMake(10, 10, 20, 20)];
/*
* Make the view you want here.
*/
UIBarButtonItem *leftBtnItem = [[UIBarButtonItem alloc] initWithCustomView:BtnView];
// Set left button.
self.navigationItem.leftBarButtonItem = leftBtnItem;
[BtnView release];
[leftBtnItem release];