如果您不想添加导航控制器,您可以使用 presentViewController 在现有视图控制器之间进行转换,从第一个到第二个,然后 dismissViewControllerAnimated 返回。
假设您使用的是 NIB(否则您只需对故事板使用 embed 命令),如果您想添加与您的 NIB 保持一致的导航控制器,您可以相应地更改您的应用程序委托。
所以,您可能有一个应用委托,它会说:
// AppDelegate.h
#import <UIKit/UIKit.h>
@class YourViewController;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) YourViewController *viewController;
@end
更改此项以添加导航控制器(您可以在此处摆脱对主视图控制器的先前引用):
// AppDelegate.h
#import <UIKit/UIKit.h>
//@class YourViewController;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
//@property (strong, nonatomic) YourViewController *viewController;
@property (strong, nonatomic) UINavigationController *navigationController;
@end
然后,在您的应用委托的实现文件中,您有一个 didFinishLaunchingWithOptions,它可能是这样的:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[YourViewController alloc] initWithNibName:@"YourViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
return YES;
}
你可以改成这样说:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
//self.viewController = [[YourViewController alloc] initWithNibName:@"YourViewController" bundle:nil];
//self.window.rootViewController = self.viewController;
YourViewController *viewController = [[YourViewController alloc] initWithNibName:@"YourViewController" bundle:nil];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
return YES;
}
完成此操作后,您现在可以使用 pushViewController 从一个 NIB 视图控制器导航到另一个视图控制器,并返回 popViewControllerAnimated。在您的viewDidLoad 中,您还可以使用self.title = @"My Title"; 命令来控制视图导航栏中显示的内容。您可能还希望更改 NIB 中的“顶部栏”属性以包含导航栏模拟指标,以便您可以布局屏幕并很好地了解它的外观:
很明显,如果您有一个非 ARC 项目,那么那些带有视图控制器的 alloc/init 的行也应该有一个 autorelease(当您查看您的应用委托时会很明显)。