The Awesome Guy
The Awesome Guy

Reputation: 332

Going back two UIViewControllers using segues

In my iOS app, I have four UIViewControllers, and for the sake of argument let's call them 1, 2, 3, and 4. I have segues leading from one to the next progressively (1->2, 2->3, 3->4). However, in 4 I want there to be a button that can segue back to one. I only pictured one way of doing this, but I couldn't figure out how to implement it...

This way would be to have a segue directly connecting 4->1, and when the segue is called delete 2 and 3 from memory (otherwise the user could keep building up UIViewControllers since none of them are being removed). I don't know how to delete them from memory since I don't have any variables pointing to them (that is, they were created when their respective segues were called, so as far as I know I don't have direct access to them).

I don't know if that's the best way, but if you can figure out how to do that (or a better way), any help is appreciated :)

Upvotes: 2

Views: 1779

Answers (2)

Ryan Poolos
Ryan Poolos

Reputation: 18561

You need to use a UINavigationController if you aren't already.

Then in your 4th view you just need a button with a selector that does the following:

- (IBAction)goBackToFirstView:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

This will handle all your memory for you and send you back to the first view controller by popping everything else off the stack.

Upvotes: 2

mweathers
mweathers

Reputation: 951

    NSArray *array = [NSArray arrayWithObject:[navigationController.viewControllers objectAtIndex:navigation.viewControllers.count-1]];
    navigationController.viewControllers = array;

Then perform the segue.

Upvotes: 0

Related Questions