在iOS中以编程方式创建UINavigationController

时间:2014-04-10 07:37:47

标签: ios uinavigationcontroller

我是iOS新手。我想在我的应用程序中使用导航控制器,但我不知道如何做到这一点。因此,任何人都可以一步一步地指导我在我的应用程序中创建导航。

6 个答案:

答案 0 :(得分:14)

appDelegate.h

@property (strong, nonatomic) UINavigationController *navController;

并设置委托UINavigationControllerDelegate并在appDelegate.m中合成对象 现在,

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设置为UINavigationControllerUINavigationController添加到UIWindow,如

self.window.rootViewController = self.navController

希望这可以帮到你

答案 1 :(得分:3)

如果要以编程方式创建所有内容,则必须在AppDelegate中执行此操作。

但是如果您不想以编程方式进行操作,那么只需在Storyboard中选择ViewController,然后选择菜单选项:

编辑 - >嵌入 - >导航控制器

答案 2 :(得分:1)

您可以在Appdelegate中创建UINavigationController并在其上设置您的第一个viewcontroller。

答案 3 :(得分:1)

因此,在不使用故事板的情况下以编程方式创建UINavigationController,请转到您的app delegate并执行以下操作。创建两个属性,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;
}

答案 4 :(得分:1)

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ImageViewController2 *dealVC = (ImageViewController2 *)[storyboard instantiateViewControllerWithIdentifier:@"ImageViewController2"];
[self.navigationController pushViewController:dealVC animated:YES];

其中ImageViewController2是类名

答案 5 :(得分:0)

以下是您应该在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;