patrickhuang94
patrickhuang94

Reputation: 2115

Segue from TableView to Navigation Controller in Swift

I currently have a navigation controller that directs to the table view that displays all the people I'm currently chatting (ChatroomTableViewController). Once I click one of the messages in my table view, I'm brought into the actual message and into a view controller (MessageViewController).

Problem: I now need a back button MessageViewController, which means I now need to add a navigation controller. This is my current code (for without a navigation controller in front of MessageViewController):

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let sb = UIStoryboard(name: "Main", bundle: nil)
    let messagesVC = sb.instantiateViewControllerWithIdentifier("MessageViewController") as! MessagesViewController
    //Some code here
    let room = results?.last as! PFObject
    messagesVC.room = room
}

Instead of instantiating MessageViewController, I want to instantiate the navigation controller that will point to MessageViewController.

Attempt:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let sb = UIStoryboard(name: "Main", bundle: nil)
    let messagesVC = sb.instantiateViewControllerWithIdentifier("NavigationViewController") as! UINavigationController
    //Some code here
    let room = results?.last as! PFObject
    messagesVC.room = room //ERROR! "UINavigationController does not have a member named 'room'"

How do I fix it?

Upvotes: 0

Views: 49

Answers (1)

avismara
avismara

Reputation: 5149

You can do something like this:

let navigationVC = sb.instantiateViewControllerWithIdentifier("NavigationViewController") as! UINavigationController
let messagesVC = naviagionVC.viewControllers[0] as! MessagesViewController
let room = results?.last as! PFObject
messagesVC.room = room

This is assuming that your MessagesViewController is the rootViewController of your design.

EDIT

Here is how navigation controller works: Suppose you have a hierarchy of view controllers: AViewController - BViewControler - CViewController which you would want to embed in a navigation controller. What you do is, you create a navigation controller and make AViewController the rootViewController and then "push" BViewController and later CViewController. Both BViewControler and CViewControler will get back buttons; AViewController doesn't since it is the root.

In your case, the VC which has the table view should be the rootViewController. And on tap of the cell, you should push the MessagesViewController which will have a back button, on click of which it will pop to your current view controller.

Upvotes: 1

Related Questions