RDowns RDowns - 5 months ago 18
iOS Question

What is the missing command to carry the cell title from UITableView to new ViewController via this segue?

I have

that contains a
. Data is loaded into that table via the following code:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UsernameSentDelegate {

@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var receiveUsername: UILabel!
@IBOutlet weak var userEmailText: UILabel!
var userEmail: String?

var communities = [String]() { didSet { communitiesTableView.reloadData()
var flag = false

@IBOutlet weak var communitiesTableView: UITableView!

@IBAction func unwindToHome(_ segue: UIStoryboardSegue) {


//recieves email address from delegate from LoginViewController
func userLoggedIn(data: String) {

userEmailText.text = data

override func viewDidLoad() {

self.communitiesTableView.delegate = self
self.communitiesTableView.dataSource = self


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return self.communities.count

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let title = self.communities[indexPath.row]

let cell = UITableViewCell()

cell.textLabel?.text = title

return cell


I then set up 1 prototype cell within the
so I could create a segue to my second view controller,
and named this segue,

I have a label set up and ready to use as the title of the cell name carried across, named

I have set up the following function to deal with the segue, including the destination variable for the cell title that has been selected.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

self.performSegue(withIdentifier: "showCommunitySegue", sender: self)
showCommunityController.communityName = //what do I put here?

What do I need to put on that last line so
displays the cell title?


Just declare selectedCellTitle as String in your viewController where your cells are.

var selectedCellTitle: String?

This will be the global variable keeping track of the selected cell's title.

Add the following in didSelectRowAt:

      func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Set your global variable to the title
            self.selectedCellTitle = self.communities[indexPath.row]
// Trigger your segue
            performSegue(withIdentifier: "showCommunitySegue", sender: self)

Override prepareforsegue method the following way:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == "showCommunitySegue" {
// Check if the segue's destination viewcontroller is your viewcontroller
                if let showCommunityController = segue.destination as? ShowCommunityViewController {
// Assign the selected title to communityName
                    showCommunityController.communityName = self.selectedCellTitle