[英]How can I pass the data from a TableViewController when I dismiss it?
I have a segue from my MainViewController to my ThemesTableViewController . 我从MainViewController到ThemesTableViewController有一个问题 。 After performing the segue, I choose a theme on my ThemesTableViewController . 执行完序列后,我在ThemesTableViewController上选择一个主题。 When I dismiss my ThemesTableViewController , I want to see the theme selected already applied to my MainViewController . 当我关闭ThemesTableViewController时 ,我想查看已应用于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)
}
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.
}
}
Passing data with unwind segue : Passing data with unwind segue 使用unsease segue 传递数据 :使用unsease segue 传递数据
Using NotificationCenter for applying theme after unwind : Adding dark mode to iOS app 展开后使用NotificationCenter应用主题: 向iOS应用添加暗模式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.