Asim Roy
Asim Roy

Reputation: 10226

Navigating different table-cell to different UIVewController in Swift

I am sorry for echoing same question but after a lot of time spending I could not figure out the issue.

Suppose, a UITableView have 2 table_cell s and I want to navigate different UIViewController from each table_cell. How do I do that?

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

                if indexPath.row == 0 {

                    // go to DetailVC_1

                } else if indexPath.row == 1 {

                    // go to DetailVC_2

        }

enter image description here

Upvotes: 1

Views: 1324

Answers (2)

Pranav Wadhwa
Pranav Wadhwa

Reputation: 7746

Try this:

if indexPath.row == 0 {
         self.performSegueWithIdentifier("firstViewController", sender: self)
} else if indexPath.row == 1 {
         self.performSegueWithIdentifier("secondViewController", sender: self)
}

If you have several view controllers, you can call them viewController0 and viewController1 etc. Then you can have a string "viewController" + String(indexPath.row). Hope this helps.

Upvotes: 0

Joris Kluivers
Joris Kluivers

Reputation: 12081

Either present a new view controller manually:

self.presentViewController(controller, animated:true, completion:nil)
// or push on a navigation controller
self.navigationController.pushViewController(controller, animated:true)

Or perform a segue you set up in a storyboard earlier. (Drag from the view controller to another view controller in your storyboard).

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

When using storyboards you can also use multiple cell types and setup a segue from each cell type to a new controller. This way the new controller will be presented automatically. The only code you might need to use in that case would be a prepareForSegue method where you pass the correct information to the presented controller before the segue is performed.

Upvotes: 3

Related Questions