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!
- Embedded your
TableViewController
inNavigation Controller
( Most probably , you already did ) .
- Select Yellow marked
TableViewController
clickRight Mouse
hold and put it to a view controller , release and select Manual Segue -> Show
Now select segue and rename it with unique Identifier . For every view controller repeat steps 2 & 3 .
Update
tableView didSelectRowAt
delegate function like below .
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { performSegue(withIdentifier: orchard[indexPath.row], sender: self) }