Xcode 8 table displays cells with different views

advertisements

I am having trouble with linking view controllers to table view cells. Basically I have 4 cells in my Table View, and I want each cell to present a separate view controller when clicked.

Here are my swift codes:

import UIKit

var orchard = ["Dog", "Cat", "Bird", "Fish"]
var myIndex = 0

class AnimalList: UITableViewController {

    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return orchard.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        cell.textLabel?.text = orchard[indexPath.row]

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        myIndex = indexPath.row
        performSegue(withIdentifier: "segue", sender: self)
    }
}

Here is my storyboard, as you can see I have 4 view controllers that I want to connect to the 4 table view cells. storyboard

PS: My table view controller has already been embedded inside a navigation controller.

How do I do that? Thank you!


  1. Embedded your TableViewController in Navigation Controller ( Most probably , you already did ) .

  1. Select Yellow marked TableViewController click Right Mouse hold and put it to a view controller , release and select Manual Segue -> Show

  1. Now select segue and rename it with unique Identifier . For every view controller repeat steps 2 & 3 .

  2. Update tableView didSelectRowAt delegate function like below .

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { performSegue(withIdentifier: orchard[indexPath.row], sender: self) }