我有一个ApplicationDelegate实现的协议。我想将它传递给故事板中定义的第一个视图控制器。如何从方法中访问它?
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
答案 0 :(得分:22)
我不确定我是否正确理解了这个问题我想你是在问如何在故事板中获得第一个viewController。为了得到这个,你打电话,
UIStoryboard *storybord = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *vc =[storybord instantiateInitialViewController];
更改故事板的名称以适合您的姓名,MainStoryboard只是默认名称。希望这是你想要的。
编辑:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UIStoryboard *storybord = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *vc =[storybord instantiateInitialViewController];
//set the delegate on the view controller that you have loaded
// Override point for customization after application launch.
return YES;
}
答案 1 :(得分:15)
而不是使用
创建现有故事板的新副本UIStoryboard *storybord = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
您可以在app app delegate的头文件中设置此属性
@property (nonatomic, weak) UIViewController* initialViewController;
并在此方法中只需将self.window.rootViewController指定给属性
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.initialViewController = self.window.rootViewController;
return YES;
}
这应该有效,因为在app delegate协议的window属性中访问rootViewConroller,如果使用storyboard,这个控制器是initialViewController。
答案 2 :(得分:-2)
为那些想要的人实施Swift 2.0。
您可能需要修改STROYBAORD和控制器视图标识符。也是
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let storyboard: UIStoryboard = UIStoryboard(name: "[STORYBOARD NAME]", bundle: nil)
let viewController:UIViewController = storyboard.instantiateViewControllerWithIdentifier("[CONTROLLER IDENTIFIER]") // You have replace UIViewController with you customer controll type
self.window?.rootViewController = viewController
self.window?.makeKeyAndVisible()
return true
}