使用委派在两个以上的视图控制器之间传递数据 仅供参考,这是ViewController3的外观

问题描述

首先,我要说的是,我已经使用委派模式在视图控制器之间来回传递数据了一段时间,没有任何问题,但是现在我需要在四(4)个视图控制器之间传递数据,ViewController1ViewController2ViewController3CategoriesViewController

在下面的代码中,我显示ViewController1CategoriesViewController间的通信,ViewController2CategoriesViewController间的通信也将相同。

我的问题或我不太喜欢的事实是我不需要在ViewController3CategoriesViewController之间传递任何数据,因此,我的辩论是如何处理这一事实。 CategoriesViewController期望变量categoryTracker,将ViewController3CategoriesViewController连接时不会传递该变量。

有没有一种方法可以使categoryTracker中的变量CategoriesViewController成为可选变量,在这里我的意思是说,从ViewController3连接时不必传递它,并且不是Swift可选项目?

你们将如何以CategoriesViewController变得模块化/可重用的方式进行此类交流?

ViewController1和ViewController2

class ViewController1: UIViewController,CategoryDelegate{

    @IBAction func showCategories(_ sender: Any) {
        let storyboard = UIStoryboard(name: "Main",bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "categoriesViewControllerID") as? CategoriesViewController
        
        vc?.delegate = self
        vc?.categoryTracker = self.categorySelection
        
        self.present(vc!,animated: true,completion: nil)
    }
}

CategoriesViewController

protocol CategoryDelegate {
    func selectedCategory(category: Category)
}

class CategoriesViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    var delegate: CategoryDelegate?
    var categoryTracker:Category?

    func tableView(_ tableView: UITableView,didSelectRowAt indexPath: IndexPath) {
        delegate?.selectedCategory(category: categoryTracker!)
    }
}

仅供参考,这是ViewController3的外观。

class ViewController3: UIViewController{

    @IBAction func showCategories(_ sender: Any) {
        let storyboard = UIStoryboard(name: "Main",bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "categoriesViewControllerID") as? CategoriesViewController            
        self.present(vc!,completion: nil)
    }
}

谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)