-2

I've got this problem, in the gif attached you can see it: if I tap on the row of UrgenzaViewController it gets back to Ho fumatoViewController, and what I need is that the Label in UITableViewCell "Urgenza" will be modified with the title of the row pressed in UrgenzaViewController. How to modify the label in the custom cell? Thanks everybody

enter image description here

Elia Crocetta
  • 318
  • 1
  • 6
  • 20

1 Answers1

2

In your Urgenza view controller create a delegate at the top of your file (above your class declaration, below the import statements) like this:

protocol UrgenzaDelegate: class {
    func menuItemSelected(item: String)
}

Then inside your Urgenza class declaration create an instance of the delegate like this :

weak var delegate: UrgenzaDelegate?

Then inside didSelectRowAtIndexPath method I would call the delegate method like this:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let delegate = delegate {
        delegate.menuItemSelected(item: dataSource[indexPath.row])
    }
}

Replace 'dataSource' with whatever data source you are using to populate the cell labels.

Finally, in your initial view controller (Ho fumatoViewController) you need to conform to the delegate you just created. You can do this by making an extension like this :

extension fumatoViewController: UrgenzaDelegate {
    func menuItemSelected(item: String) {
        // Here is where you save the selected item to whatever data source you are using
        tableView.reloadData()
    }
}

And lastly, and very important!, wherever you are pushing the Urgenza view controller you must set yourself to its delegate property like so:

    let vc = UrgenzaViewController()
    vc.delegate = self // This is the important part!
    self.present(vc, animated: true, completion: nil)
LoganHenderson
  • 1,222
  • 4
  • 12
  • 24