以编程方式在iOS中创建UINavigationController
我是iOS新手。 我想在我的应用程序中使用导航控制器,但我不知道该怎么做。 因此,任何人都可以一步一步地指导我在我的应用程序中创建导航。
在appDelegate.h中
@property (strong, nonatomic) UINavigationController *navController;
现在,在appDelegate.m
设置委托UINavigationControllerDelegate
和合成对象,
appDelegate.m
您可以在didFinishLaunchingWithOptions
方法中设置导航控制器
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. frstVwCntlr = [[firstViewController alloc] initWithNibName:@"firstViewController" bundle:nil]; self.navController = [[UINavigationController alloc] initWithRootViewController:self.frstVwCntlr]; self.window.rootViewController = self.navController; self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; return YES; }
在上面的代码中,你的firstViewController设置为UINavigationController
, UINavigationController
添加到UIWindow
self.window.rootViewController = self.navController
希望这可以帮到你
如果要以编程方式创建所有内容,则必须在AppDelegate中执行此操作。
但是,如果您不想以编程方式执行此操作,则只需在Storyboard中选择ViewController,然后选择菜单选项:
编辑 – >嵌入 – >导航控制器
您可以在Appdelegate中创建UINavigationController并在其上设置您的第一个viewcontroller。
因此,要以编程方式创建UINavigationController而不使用故事板,请转到您的应用程序委托并执行以下操作。 创建两个属性,window和viewController
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.backgroundColor=[UIColor clearColor]; self.viewController = [[YourFirstViewController alloc] initWithNibName:@"YourFirstViewController" bundle:nil]; UINavigationController *navController=[[UINavigationController alloc]initWithRootViewController:self.viewController]; self.window.rootViewController = navController; [self.window makeKeyAndVisible]; // Override point for customization after application launch. return YES; }
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; ImageViewController2 *dealVC = (ImageViewController2 *)[storyboard instantiateViewControllerWithIdentifier:@"ImageViewController2"]; [self.navigationController pushViewController:dealVC animated:YES];
其中ImageViewController2是一个类名
这是您应该在app delegate中编写的代码。
UIViewController *vc=[[UIViewController alloc]initWithNibName:@"vc1" bundle:nil]; UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 568)]; view.backgroundColor=[UIColor redColor]; [vc setView:view]; self.navme=[[UINavigationController alloc]initWithRootViewController:vc]; self.window.rootViewController = self.navme;
对于Swift 3.0,使用filter:
let desiredController = self.navigationController!.viewControllers.filter { $0 is YourController }.first! self.navigationController!.popToViewController(desiredController, animated: true)