I have a couple of UIViewControllers
like shown
What I want is to pass data from B to C and also do that transition. So far I've come with 2 possible solutions:
UIViewController
class (and save a reference of the data in it), pop B from the navigation controller
and push C into it. navigation controller
and then, in the viewWillAppear
method of A, check if the data is not nil to know if it should send it to C and perform the segue
. Should I take any of those 2 approaches? Or is there a more elegant/proper solution for this situation?
Thanks
Organize data manager of parent controller or use Core Data.
In case of keeping data in parent controller, use dependency injection like described here
Here is an example for your case:
var dataFromC = "" // or nil
var dataFromB = "" // or nil
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "B",
let viewController = segue.destinationViewController as? BViewController {
viewController.dataFromC = self.dataFromC
// declare method in BViewController
// var method : ((String) -> ())? = nil
viewController.method = {[weak self] valueFromB in
self?.dataFromB = valueFromB
}
}
if segue.identifier == "C",
let viewController = segue.destinationViewController as? CViewController {
viewController.dataFromB = self.dataFromB
// declare method in CViewController
// var method : ((String) -> ())? = nil
viewController.method = {[weak self] valueFromC in
self?.dataFromC = valueFromC
}
}
}
If you want to pass value to parent controller from BViewController
, use self.method("yourValueFromB")
where you will change the value. For case with CViewController
use same approach.
As a general practice, B should send the data back to its originating view controller A with the help of delegate protocol pattern. A should be able to then decide in the delegate method implementation, what the data is received from B and where to send this data, which in this case is C.
This way your code looks more organised.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.