以编程方式设置/激活Segue

时间:2014-03-29 10:56:23

标签: ios objective-c xcode-storyboard

我尝试在iOS应用程序中设置首次启动视图。为此,我有以下代码,允许我在第一次启动应用程序时执行代码。

我想要的是,当应用程序第一次启动时,用户被发送到我在Storyboards中设置的FirstLaunch视图,而不是FirstView视图。每次连续启动都会将用户发送到FirstLaunch视图。

目前,我已在NavigationController.m中执行此代码,但如果在AppDelegate.m中更好地执行此代码,我可以更改它。

if ([[NSUserDefaults standardUserDefaults] boolForKey:@"FirstLaunch"])
{
    // not first launch
}
else
{
    // first launch

    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"FirstLaunch"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

我的问题是:如何设置segue可编程(或激活segue)以将用户发送到FirstLaunch视图而不是普通的FirstView?

4 个答案:

答案 0 :(得分:0)

在你的故事板中设置你需要的segue标识符(选择segue并选择Attributes Inspector)。

之后,您可以通过编程方式调用segue:

[self performSegueWithIdentifier:@"indentifier" sender:nil];

答案 1 :(得分:0)

这篇关于segue的解释很好的文章将回答你的问题

http://www.appcoda.com/storyboards-ios-tutorial-pass-data-between-view-controller-with-segue/

使用segue激活和传递数据的示例块:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showRecipeDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        RecipeDetailViewController *destViewController = segue.destinationViewController;
        destViewController.recipeName = [recipes objectAtIndex:indexPath.row];
    }
}

答案 2 :(得分:0)

答案 3 :(得分:0)

您不需要segue - 您需要的只是一种以编程方式选择初始视图控制器的方法,具体取决于它是否是第一次启动。

为此,请在FirstView的故事板中取消选中“是初始视图控制器”,然后按如下方式更改您的应用代理:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
    // Use the name of your storyboard below
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MyStoryboard" bundle:nil];
    NSString *initialId;
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"FirstLaunch"]) {
        // not first launch
        initialId = @"FirstViewController";
    } else {
        // first launch
        initialId = @"FirstLaunchViewController";    
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"FirstLaunch"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    self.window.rootViewController = [storyboard instantiateViewControllerWithIdentifier:initialId];
    [self.window makeKeyAndVisible];
    return YES;
}

上面的代码嵌入了代码,用于决定是否是首次启动,并根据此决定设置目标屏幕的故事板标识符。

请注意,此实现永远不会再次向用户显示第一个启动屏幕,即使他第一次出现时也没有机会好好看一下(例如因为有人打电话给他,或者设备运行了没电了电池)。更好的方法是以与您相同的方式读取NSUserDefaults,但仅在用户解除第一个启动控制器时将其设置为YES。这样您就可以确定用户有足够的时间看到屏幕并与之交互。

相关问题