Tyler Middleton Tyler Middleton - 2 months ago 12
Swift Question

Move Text from cell to text label in a different view controller

I have created an app that displays 10 random numbers in a table view. This is the code I used

override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}


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

// Configure the cell...
cell.textLabel?.text = "\(indexPath.row + 1): \(Int(arc4random_uniform(10001)))"

return cell
}


Now I want to be able to click on one cell and be taken to another view controller and in the center of the page it displays the random number. I have the view controller all set up and linked to the original table view. I'm just having trouble passing my data through the segue. This is what I have so far. I know it unfinished, I just don't know what to do.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showRandomNumber" {
let controller = segue.destination as! ShowNumberTableViewController
let selectedRow = (tableView.indexPathForSelectedRow as NSIndexPath?)?.row ?? 0
controller.LabelText =
}


The LabelText is the name of the label that I want to pass the data to, but I don't know how to

Answer

Using the indexPathForSelectedRow, you can get a reference to the cell that triggered the segue. You can then access the textLabel within that cell, get its value, and pass it to the next view controller.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {   
    if segue.identifier == "showRandomNumber" {
        let controller = segue.destination as! ShowNumberTableViewController
        if let indexPath = tableView.indexPathForSelectedRow {
            let cell = tableView.cellForRowAtIndexPath(indexPath) as UITableViewCell
            if let textToPass = cell.textLabel.text {
                controller.labelText = textToPass
            }
        }
    }
}

Then in ShowNumberTableViewController you want a var labelText and in your viewDidLoad() you can assign it to the textLabel in that view controller with

centerLabel.text = labelText
Comments