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

时间:2010-06-04 12:58:26

标签: iphone cocoa-touch xcode uiviewcontroller interface-builder

我首选,在设置时,强制我的应用程序在启动时执行某些同步。

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

是否有一种标准方法可以启用此行为?

1 个答案:

答案 0 :(得分:3)

假设您在同步期间设置了app委托的属性,在初始视图控制器的initWithNibNamed:方法中检查app委托同步的值并通过调用[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;
}