swiftcode
swiftcode

Reputation: 3059

How to get an already instantiated UIViewController?

I'm new to iOS programming, and I'm using the ECSlidingViewController to create a slide out menu (like Facebook). So imagine if I have two views referenced in my menu.

When I open the app, it will obviously call viewDidLoad for my top view (the first one in my menu). If I open the menu and select the second view, it will call viewDidLoad for that too. However, if I go back to the first view, it will call that method again, which I don't want. I have some setup code and I don't want to be reinstantiating views if possible. I've seen Facebook and they don't reinstatiate views, because it remembers my scrolling position on my Wall, for example, when after I switch views and go back.

This is my delegate method that triggers upon selection:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Get identifier from selected
    NSString *identifier = [NSString stringWithFormat:@"%@", [self.menu objectAtIndex:indexPath.row]];

    // Add the selected view to the top view
    UIViewController *newTopVC = [self.storyboard instantiateViewControllerWithIdentifier:identifier];

    // Present it 
    [self.slidingViewController anchorTopViewOffScreenTo:ECRight animations:nil onComplete:^{
        CGRect frame = self.slidingViewController.topViewController.view.frame;
        self.slidingViewController.topViewController = newTopVC;
        self.slidingViewController.topViewController.view.frame = frame;
        [self.slidingViewController resetTopView];
    }];
} 

Is there a way to somehow get a certain VC if it's already been created? That way, it will only call viewWillAppear, and not viewDidLoad more than once.

Thank you.

Upvotes: 0

Views: 1432

Answers (1)

lakshmen
lakshmen

Reputation: 29094

Can Use a navigationcontroller. When you want to go to second view, you can push it the viewcontroller onto the navigation view controller and when you go back, you can pop it off the navigation controller.

EDIT:

If you have 3 views, you can still use navigationcontroller. Same logic as above. But remember to remove the double instances of the same viewcontroller in the navigationcontroller. Look at this page: How to remove a specific view controller from uinavigationcontroller stack?. Check whether the particular viewcontroller exist, if so, remove and then push it on top.

Upvotes: 1

Related Questions