代码之家  ›  专栏  ›  技术社区  ›  Brandon

根据应用程序首选项加载不同的初始视图?

  •  1
  • Brandon  · 技术社区  · 15 年前

    我有一个首选项,设置后,强制应用程序在启动时执行某些同步。

    我可以使用ib根据此设置显示不同的初始视图吗?

    是否有标准的方法来启用此行为?

    1 回复  |  直到 15 年前
        1
  •  3
  •   falconcreek    15 年前

    假设您的应用程序委托上有一个在同步过程中设置的属性,在初始视图控制器的initWithNibNamed:方法中,检查应用程序委托同步的值,并通过调用 [super initWithNibNamed:@"thisNibInsteadOfThatNib"];

    编辑: 根据启动时的某些条件,显示用于启动其他视图的代码

    // AppDelegate.h
    #import <UIKit/UIKit.h>
    
    @interface AppDelegate : NSObject <UIApplicationDelegate>
    {
        UIWindow *window;
        UIViewController *firstViewController;
    }
    @property {nonatomic, retain} UIWindow *window;
    @end
    
    // AppDelegate.m
    #import AppDelegate.h
    #import ViewControllerOne.h
    #import ViewControllerTwo.h
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        BOOL shouldLoadViewOne = \\ some value from preferences
    
        if (shouldLoadViewOne) {
            firstViewController = [[ViewOneController alloc] initWithNibName:@"ViewOneController" bundle:nil];
        } else {
            firstViewController = [[ViewTwoController alloc] initWithNibName:@"ViewTwoController" bundle:nil];
        }
    
        UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:firstViewController];
    
        [window addSubView:[navController view]];
    
        [window makeKeyAndVisible];
    
        return YES;
    }
    

    编辑2:

    利用 NSClassFromSting() 并保存FirstViewController的名称以加载到首选项中。

    // AppDelegate.h
    #import <UIKit/UIKit.h>
    
    @interface AppDelegate : NSObject <UIApplicationDelegate>
    {
        UIWindow *window;
        id firstViewController;
    }
    @property {nonatomic, retain} UIWindow *window;
    
    - (NSString *)firstViewControllerName;
    
    @end
    
    // AppDelegate.m
    #import AppDelegate.h
    #import ViewControllerOne.h
    #import ViewControllerTwo.h
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        NSString *viewControllerName = [self firstViewControllerName];
    
        firstViewController = [[NSClassFromString(viewControllerName) alloc] initWithNibName:viewControllerName  bundle:nil];
    
        UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:firstViewController];
    
        [window addSubView:[navController view]];
    
        [window makeKeyAndVisible];
    
        return YES;
    }
    
    - (NSString *)firstViewControllerName
    {
        NSString *defaultViewController = @"ViewOneController";
        NSString *savedFirstViewController = // string retrieved from preferences or other persistent store
    
        if (!savedFirstViewController)
            return defaultViewController;
    
        return savedFirstViewController;
    }
    
    推荐文章