【问题标题】:Get the main storyboard at runtime在运行时获取主情节提要
【发布时间】:2013-10-11 21:36:29
【问题描述】:

我希望能够在运行时简单地调用 [UIStoryboard mainStoryboard] 来获取 iPad 或 iPhone 故事板。

【问题讨论】:

    标签: ios objective-c cocoa-touch uistoryboard


    【解决方案1】:

    这是一个 UIStoryboard 类别,它可以做到这一点:

    UIStoryboard+LDMain.h

    #import <UIKit/UIKit.h>
    
    @interface UIStoryboard (LDMain)
    
    + (instancetype)LDMainStoryboard;
    
    @end
    

    UIStoryboard+LDMain.m

    #import "UIStoryboard+LDMain.h"
    
    UIStoryboard *_mainStoryboard = nil;
    
    @implementation UIStoryboard (LDMain)
    
    + (instancetype)LDMainStoryboard {
        if (!_mainStoryboard) {
            NSBundle *bundle = [NSBundle mainBundle];
            NSString *storyboardName = [bundle objectForInfoDictionaryKey:@"UIMainStoryboardFile"];
            _mainStoryboard = [UIStoryboard storyboardWithName:storyboardName bundle:bundle];
        }
        return _mainStoryboard;
    }
    
    @end
    

    这是link to the gist

    【讨论】:

    • 框架类的类别应始终使用前缀以避免名称冲突。
    • 谢谢。我已经进行了更改。
    • 酷;不过,方法名称实际上是更重要的部分。
    • 真的没有这么简单。这将为您提供主故事板的副本。如果你反复这样做,你每次都会得到故事板的新副本。
    • 嗯,主要是?如果您已经通过常规应用程序启动加载了故事板,您将拥有它的两个副本。这可能比 N 个副本更好。 :)
    【解决方案2】:

    如果情节提要尚未加载,您可以使用[UIStoryboard storyboardWithName:storyboardName bundle:bundle]

    但是,如果有,这将加载一个新副本。

    您也可以使用viewController.storyboard 来获取现有的。如果你有一个mainWindow 作为你的应用程序委托的一部分(你可能有),你可以获得rootViewController.storyboard

    类似:

    UIApplication *application = [UIApplication sharedApplication];
    MyAppDelegate *myAppDelegate = ((MyAppDelegate *)application).delegate;
    return myAppDelegate.mainWindow.rootViewController.storyboard;
    

    如果没有,这可能对你有用:

    UIApplication *application = [UIApplication sharedApplication];
    UIWindow *backWindow = application.windows[0];
    return backWindow.rootViewController.storyboard
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-01
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 2010-11-29
      • 2015-10-02
      • 1970-01-01
      • 2015-12-10
      相关资源
      最近更新 更多