我正在尝试使用 UINavigationController,但不确定如何使用。到目前为止(大约一年),我一直在使用 presentModalViewController 和 dismissModalViewController 来显示/关闭 View Controller 。
所以,这就是我所做的。我的主视图 Controller (启动时显示的第一个)称为 MainViewController,它扩展了 UIViewController。
所以我在我的应用委托(delegate)中创建了这个启动函数:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
MainViewController *controller = [[MainViewController alloc] init];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:controller];
[self.window addSubview:navigationController.view];
[self.window makeKeyAndVisible];
return YES;
}
在我的 MainViewController 的 viewDidLoad 方法中:
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"Title";
self.navigationController.navigationBar.tintColor = [Constants barColor];
....more code...
}
但是,在我的 MainViewController 中,我想展示另一个名为 SecondViewController 的 View Controller ,它需要一个带有后退箭头按钮的 UINavigationBar。那么我是否让 SecondViewController 扩展 UIViewController 并通过在 viewDidLoad 方法中设置标题和 backButton 来做同样的事情?我该如何展示它?我应该怎么做才能做到这一点?
最佳答案
您需要设置 Root View Controller ,从苹果模板开始最简单。
神奇之处在于:
UIViewController *controller = [[UIViewController alloc] initWithNibName:@"MyNib" bundle:nil];
[self.navigationController pushViewController:controller animated:YES];
[controller release];
导航 Controller 为您完成所有工作(后退按钮、标题、动画)——它会跟踪!
我的工作流程是这样的:
在 viewDidLoad 中设置 MutableArray,为其添加 Controller ,例如:
NSMutableArray *array = [[NSMutableArray alloc] init];
MyCustomViewController *customView = [[MyCustomViewController alloc] initWithNibName:@"nib" bundle:@"nil"];
customView.title = @"Second Level";
[array addObject:customView];
self.controllers = array;
然后在你的委托(delegate)中:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
UIViewController *childControllerToBe = [controllers objectAtIndex:row];
[self.navigationController pushViewController:childControllerToBe animated:YES];
}
通过阅读像 Beginning iPhone Development 这样的一本不错的初学者书籍,可以学到更多的东西。
此外,apple docs总是好的:)
关于iphone - UINavigationController - 基础知识,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6672300/