如何正确地将数据传递给以前的 viewController(有导航)?
Posted
技术标签:
【中文标题】如何正确地将数据传递给以前的 viewController(有导航)?【英文标题】:How can I properly pass data to previous viewController(which has navigation)? 【发布时间】:2021-01-06 13:46:41 【问题描述】:我想将文本数据从当前 viewController(vcB) 传递到前一个 viewController(vcA)。两个 viewControllers 都有 navigationBar,它通过下面的代码从 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 的正确方法是什么?
【问题讨论】:
可以使用本方法的completion参数。 【参考方案1】:像委托模式一样,我们也可以使用闭包。在这种情况下,我更喜欢 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")
【讨论】:
@MO 如果这对您有用,请接受答案.. 以便其他人可以参考。【参考方案2】:你可以尝试像下面这样传递一个回调 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)
)
【讨论】:
我尝试使用闭包传递数据,但谢谢!以上是关于如何正确地将数据传递给以前的 viewController(有导航)?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Swift(Cocoa 应用程序)中将数据传递给以前的 ViewController