Sergio Robles
Sergio Robles

Reputation: 5

How do I create an array of View Controllers?

I'm brand new when it comes to app development so this might be a stupid question. So i have made a UI table. Each row is a different topic. I want to allow users to click on a table cell and it'll direct them to another view controller. All the view controllers will have different content arranged in different ways. Any idea how to implement this using storyboard or just programatically? Appreciate it!

Upvotes: 0

Views: 3926

Answers (1)

Mike
Mike

Reputation: 9835

To answer the main question of the post, here is how you create an array of view controllers:

// create your view controllers and customize them however you want
UIViewController *viewController1 = [[UIViewController alloc] init];
UIViewController *viewController2 = [[UIViewController alloc] init];
UIViewController *viewController3 = [[UIViewController alloc] init];

// create an array of those view controllers
NSArray *viewControllerArray = @[viewController1, viewController2, viewController3];

I'm not so sure this is what you actually need to do given your explanation, but without more information this answers the initial question.

You really don't want to create all the view controllers at once and have them sitting there in memory - you really only want to create them when they're actually needed - which is when the user selects the cell. You're going to want to do something like the following to achieve what you want to do:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (indexPath.row == 0) {
        // create the view controller associated with the first cell here
        UIViewController *viewController1 = [[UIViewController alloc] init];
        [self.navigationController pushViewController:viewController1 animated:YES];
    }

    else if (indexPath.row == 1) {
        // create the view controller associated with the second cell here
        UIViewController *viewController2 = [[UIViewController alloc] init];
        [self.navigationController pushViewController:viewController2 animated:YES];
    }

    else {
        // etc
    }
}

Upvotes: 3

Related Questions