从ViewController调用NavigationController(xib)(storyboard)

时间:2013-10-25 16:18:25

标签: ios objective-c uinavigationcontroller storyboard

我通常只是为我的iOS使用故事板,但需要集成不使用故事板的SDK,而不是xib。我的初始视图控制器来自故事板,当按下按钮(IBAction)时,我希望它转到xib视图控制器,但不确定如何以编程方式执行此操作。这是我的AppDelegate:

 //AppDelegate.m

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:...{   

// set to storyboard on launch
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"iPhoneStoryboard"
                                                         bundle: nil];

UIViewController* viewController = [mainStoryboard instantiateInitialViewController];
[self.window setRootViewController:viewController];

 [window makeKeyAndVisible];
 return YES;
 }

这是我的代码.h:

 //mainVC.h
 #import <UIKit/UIKit.h>

 @interface MainVC : UIViewController{
 UIWindow *window;
 UINavigationController *navigationController;
 }

 @property (nonatomic, retain) IBOutlet UIWindow *window;
 @property (nonatomic, retain) IBOutlet UINavigationController *navigationController;
 @property (nonatomic, retain) IBOutlet UIButton *buttonScan;

 -(IBAction) ActionScan;

 @end

而.m:

 //mainVC.m
 @interface MainVC ()

 @end

 @implementation MainVC

 @synthesize window;
 @synthesize navigationController;
 @synthesize buttonScan;

 - (IBAction)ActionScan{

window.rootViewController = navigationController;
[window makeKeyAndVisible];

 }

3 个答案:

答案 0 :(得分:0)

在故事板的视图控制器中,代码如下:

  1. alloc&amp; init目标视图控制器:

    UIViewController *desController = [[SomeViewController alloc]init];

  2. 显示目标视图控制器:

    [self.navigationController pushViewController:desController animated:YES]

    [self.navigationController presentViewController:desController animated:YES completion:nil

答案 1 :(得分:0)

通常你不直接设置窗口的rootViewController。相反,你应该使用

 - (IBAction)ActionScan{
    [self presentViewController:self.navigationController animated:YES completion:nil]; 
 }

显示您的下一个视图控制器。这个问题的第一个被接受的答案给出了更详细的解释。

Changing root view controller of a iOS Window

设置window.rootViewController并调用[window makeKeyAndVisible]通常会在你的app delegate中发生,但是因为你正在使用故事板,所以它是在幕后完成的。

此外,除非您使用多个窗口,否则您可以使用app delegate singleton对象从任何地方访问UIWindow。

MyAppDelegateClass *appDelegate = (MyAppDelegateClass*)[[UIApplication sharedApplication] delegate];
UIWindow *mainWindow = appDelegate.window;

答案 2 :(得分:0)

使用initWithNibName

创建xib viewController的实例
MyViewController *controller = [[MyViewController alloc] initWithNibName:@"MyViewController" bundle:nil];

&安培;然后在导航控制器上推送此控制器实例

[self.navigationController pushViewController:desController animated:YES]