如何将数据正确传递给以前的 viewController具有导航功能?

问题描述

我想将文本数据从当前 viewController(vcB) 传递给前一个 viewController(vcA)。两个视图控制器都有导航栏,它通过下面的代码从 vcA 转换到 vcB(它以模态转换)。

// in vcA file
let nextView = self.storyboard?.instantiateViewController(identifier: "nextView")
let nav = UINavigationController(rootViewController: nextView!)
present(nav,animated: true,completion: nil)

我想在vcB中调用dismiss方法时将数据传递给vcA,此时将文本数据保存在vcB中。 将数据传递给以前的 viewController 的正确方法是什么?

解决方法

像委托模式一样,我们也可以使用闭包。在这种情况下,我更喜欢 Closure 的例子。

class ParentViewController: UIViewController {
    
    func navigateToChildViewController() {
        let childController = ChildViewController()
        childController.selectionCompletion = { message in
            print(message) //print Hello world
        }
        self.present(childController,animated: true)
    }
}

class ChildViewController: UIViewController {
    var selectionCompletion: ((String) -> Void)?

    //method can be any,here I take example of this method
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //This callback,will pass this string value back to it's parent controller
        selectionCompletion?("Hello World")
    }
}
,

您可以尝试像下面这样传递回调 viewController B

class AController: UIViewController,ControllerDataDelegate { 
    func presentNewController() { 
        let bController = BController.get(listener: self)
        self.present(bController,animated: true)
    }

    func onDataReady(_ data: String) { 
         // do what you want with this string
    } 
}

protocol ControllerDataDelegate { 
     func onDataReady(_ data: String)
}

class BController: UIViewController { 
    class func get(listener: ControllerDataDelegate) { 
       let controller = BController.init()
       controller.listener = listener
       return controller
    }

    private var listener: ControllerDataDelegate!

    // any time you want to notify previous view controller
    func notify(with data: String) { 
        self.listener(data)
    }

    // call this function when you want to close and return some data
    func requestClose(animated: Bool = true,with data: String) { 
         self.dismiss(animated: animated,completion: { 
             self.notify(with: data)
         })
    }
}