Reputation: 491
I have a segue from my MainViewController to my ThemesTableViewController. After performing the segue, I choose a theme on my ThemesTableViewController. When I dismiss my ThemesTableViewController, I want to see the theme selected already applied to my MainViewController. How can I achieve that?
// Here's my Theme
struct Theme {
var name: String!
var backgroundColor: UIColor!
...
}
themes = [red, blue, green]
// I have no idea how I can pass chosenTheme to my MainViewController
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
chosenTheme = themes[indexPath.row]
dismiss(animated: true, completion: nil)
}
Upvotes: 0
Views: 38
Reputation: 38
protocol ThemeDelegate {
func didSelectTheme(theme: Theme)
}
var delegate: ThemeDelegate?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
chosenTheme = themes[indexPath.row]
self.delegate?.didSelectTheme(theme: chosenTheme)
}
You can create a protocol and implement it like this and pass the chosenTheme to the previous viewcontroller. In your MainViewController prepare for segue function do it like this.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if let themeVC = segue.destination as? ThemesTableViewController {
themeVC.delegate = self
}
}
Also implement an extension like this in MainViewController.
extension MainViewController: ThemeDelegate {
func didSelectTheme(theme: Theme) {
// do something with the selected theme.
}
}
Upvotes: 1
Reputation: 71
Passing data with unwind segue : Passing data with unwind segue
Using NotificationCenter for applying theme after unwind : Adding dark mode to iOS app
Upvotes: 0