Search code examples
iosswiftuitableviewsegueuistoryboardsegue

Passing data from a static tableViewCell to another viewController?


I have a tableView with static cells.

What I wan't, is that when the user selects a certain cell, the text from this cell, is passed to the previous viewController. I have never worked with static cells before and I can only seem to find tutorials and other questions regarding activating the cells, so they leed to another viewController.

So how do I pass data (what's written in the cell), when the cell is selected?

Is it a code in didSelectRowAtIndexPath?

Do I use segues? Then there will have to be hundreds of segues, if I have hundreds of cell, that the user can choose, right?

Thanks!


Solution

  • First you are assigning Array of String to DiaryQuestionLabel.text which accepts string only in destinationViewController. Just change the type of chosenQuestion to String in destinationViewController as below.

    @IBOutlet weak var DiaryQuestionLabel: UILabel!
    var chosenQuestion: String = ""
    
    override func viewDidLoad() {
       super.viewDidLoad()
       DiaryQuestionLabel.text = chosenQuestion
    }
    

    In your tableViewController You need to pass the value of selected index from your datasource array which you have used to set the data in your tableviewcell.

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
         if segue.destination is UpdatingIdentifiers {
         let vc = segue.destination as? UpdatingIdentifiers
         let selectedRowIndex = self.tableView.indexPathForSelectedRow()
         // Get tableviewcell object from indexpath and assign it's value to chosenQuestion of another controller.  
         let cell = yourtableview.cellForRow(at: selectedRowIndex)
         let label = cell.viewWithTag(420) as! UILabel
         vc?.chosenQuestion = label.text
        }
    }