当我解除它时,如何从TableViewController传递数据?

时间:2018-06-17 08:07:29

标签: ios swift

我的 MainViewController 中有一个segue到我的 ThemesTableViewController 。执行segue后,我在 ThemesTableViewController 上选择了一个主题。当我关闭 ThemesTableViewController 时,我希望看到已经应用的主题已应用于我的 MainViewController 。我怎样才能做到这一点?

// 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)
}

2 个答案:

答案 0 :(得分:1)

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.
    }

}

答案 1 :(得分:0)

使用展开segue传递数据: Passing data with unwind segue

使用NotificationCenter在展开后应用主题: Adding dark mode to iOS app