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?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Jasper
  • 8,440
  • 31
  • 92
  • 133
  • is your performsegue is pushview controller or presentview controller?? – Mukesh May 15 '15 at 10:24
  • miuku> not sure, where do i see that? The NavigationController is UINavigationController class in identity inspector. Sorry i am new to iOS, Swift – Jasper May 15 '15 at 10:28
  • 1
    your View1 is not in the navigationcontroller hierarchy, so you cannot call popViewController on navigationController to go back to View1 – Vinay Jain May 15 '15 at 10:29
  • 1
    check this ... http://stackoverflow.com/questions/12561735/what-are-unwind-segues-for-and-how-do-you-use-them – Shruti May 15 '15 at 10:30
  • Vinay> So how do i bring View1 in the navigationController hierarchy, or alternately any other solution? – Jasper May 15 '15 at 10:33
  • @Jasper you mean ViewController by View? – Ch0k0l8 May 15 '15 at 10:35

3 Answers3

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

Mukesh
  • 3,680
  • 1
  • 15
  • 32
  • 6
    **SWIFT 3.0** syntax has changed like this; `self.dismiss(animated: true, completion: nil)` – Trevor Oct 25 '16 at 14:10
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

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
  • Dharmesh> After i select the View1 in storyboard, i don't see a way to provide ID in Identity or Attribute Inspector. – Jasper May 15 '15 at 10:38
0

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

Saneesh
  • 1,796
  • 16
  • 23