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
Asked
Active
Viewed 109 times
-2
-
This is easily accomplished by delegation – OverD Aug 25 '17 at 17:15
-
OverD could you please give me an example of code? – Elia Crocetta Aug 25 '17 at 17:19
-
1you should use delegate , i will try to send you an example – Abdelahad Darwish Aug 25 '17 at 17:24
-
check this https://stackoverflow.com/questions/5210535/passing-data-between-view-controllers – Abdelahad Darwish Aug 25 '17 at 17:26
-
I already saw it, but unfortunately I don't know anything about objective-C, that's the reason why I asked how to do that in swift :( – Elia Crocetta Aug 25 '17 at 17:27
-
2@EliaCrocetta there are several Swift replies as well to that question, you should keep scrolling. – Dávid Pásztor Aug 25 '17 at 17:47
1 Answers
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
-
protocol of class types should have weak delegates.Else you created a retail cycle (memory leak).And it seems like your delegate is nil. – Tushar Sharma Aug 25 '17 at 17:56
-
-