iOS: Go back to previous view
Asked Answered
A

3

8

I have two views like this in Story Board:

[View1] -> [Navigation Controller] -> [View2]

To go from View1(has tableview) to View 2, i do this on click of a row on View1:

self.performSegueWithIdentifier("showmyview2", sender:self)

This works.

Now i have a button on View 2, which when clicked should take me back to previous view i.e View 1.

I tried this:

 navigationController!.popViewControllerAnimated(true)

But this does not work. How do i go back to first view?

Asparagus answered 15/5, 2015 at 10:22 Comment(6)
is your performsegue is pushview controller or presentview controller??Subcartilaginous
miuku> not sure, where do i see that? The NavigationController is UINavigationController class in identity inspector. Sorry i am new to iOS, SwiftAsparagus
your View1 is not in the navigationcontroller hierarchy, so you cannot call popViewController on navigationController to go back to View1Vuillard
check this ... #12562235Bushido
Vinay> So how do i bring View1 in the navigationController hierarchy, or alternately any other solution?Asparagus
@Asparagus you mean ViewController by View?Tricornered
S
32

First Add a navigation controller to your First view1 through storyboard.(Editor->Embed Navigation controller), If navigation is not present.

OR

self.dismissViewControllerAnimated(true, completion: nil);

Call this function and try instead of navigation popviewcontroller

Subcartilaginous answered 15/5, 2015 at 10:37 Comment(1)
SWIFT 3.0 syntax has changed like this; self.dismiss(animated: true, completion: nil)Underclothes
H
5

Use this code to present first view in your button action:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("FirstView") as! TableViewController
self.presentViewController(vc, animated: true, completion: nil)

And don't forget to give Id to your First view.

Select your firstView into storyBoard and then click on Identity Inspector and you can assign StoryBoard ID like show into below Image.

enter image description here

Hispanic answered 15/5, 2015 at 10:31 Comment(1)
Dharmesh> After i select the View1 in storyboard, i don't see a way to provide ID in Identity or Attribute Inspector.Asparagus
A
0

self.dismiss(animated: true, completion: nil); this will work in swift 3

Amphitheater answered 24/3, 2017 at 5:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.