Reputation: 14824
I'm dabbling in iOS app development for the first time, I have a project in mind and I'm currently working on the layout.
Basically I have a main view controller, and others (we'll just call them VC1, VC2 etc... for the sake of clarity)
App launches to VC1, you click the search button, a modal VC2 pops up with a recent, and a search bar. You type in a name and hit search, this is basically where I want it to segue Back to VC1, and then forward to VC3 (The players screen of the app)
Right now it goes VC1(SearchButtonAction) -> VC2(SearchPlayerAction) -> VC3
(but this looks weird with the transition from the modal to a view controller, and if I hit back it looks even weirder.
I want it to go
VC1(SearchButtonAction) -> VC2(SearchPlayerAction) -> VC1 -> VC3
I don't really know how to manage it or I would attach some code. Instead I've attached a screenshot of what I have working so far.
I'm not sure if I'm supposed to do something like prepareForSegue
and make a boolean to flag if it should auto-segue on loading to send to VC3, but then I need to pass the data to VC1, just to pass it back to VC3, it seems messy, I'd just like to segue / pass the same data from VC2 back to VC3, going through VC1 though. I hope that's clear x.x
Upvotes: 0
Views: 521
Reputation: 507
There are a few options that you could use.
1. Unwind Segue
I've started using these recently, they can be really useful for passing data back from one VC to another. You basically add a function in the VC that you will be unwinding back to, in your case this will be VC1. This function in VC1 will be called when you dismiss VC2. You could then push to VC3 from here.
I have attached a brief code example, but here is a link to a good tutorial that will describe it better.
EXAMPLE
VC2
class ViewController2: UIViewController
{
let dataToPassToVC3 = "Hello"
@IBAction func dismissButtonTapped(_ sender: Any)
{
self.dismiss(animated: true, completion: nil)
}
}
VC1
class ViewController1: UIViewController
{
@IBAction func unwindFromVC2(segue:UIStoryboardSegue)
{
//Using the segue.source will give you the instance of ViewController2 you
//dismissed from. You can grab any data you need to pass to VC3 from here.
let VC2 = segue.source as! ViewController2
VC3.dataNeeded = VC2.dataToPassToVC3
self.present(VC3, animated: true, completion: nil)
}
}
2. Delegate Pattern
VC2 could create a protocol that VC1 could conform to. Call this protocol function as you dismiss VC2.
EXAMPLE
VC2
protocol ViewController2Delegate
{
func viewController2WillDismiss(with dataForVC3: String)
}
class ViewController2: UIViewController
{
@IBAction func dismissButtonTapped(_ sender: Any)
{
delegate?.viewController2WillDismiss(with: "Hello")
self.dismiss(animated: true, completion: nil)
}
}
VC1
class ViewController1: UIViewController, ViewController2Delegate
{
func viewController2WillDismiss(with dataForVC3: String)
{
VC3.dataNeeded = dataForVC3
self.present(VC3, animated: true, completion: nil)
}
}
Upvotes: 3