What I am trying to do simply change views based on some data. To demonstrate exactly what I am trying to do I have constructed a little example to demonstrate. I used a UISegmentedControl to simulate data data then when a button is pressed, it would switch between views based on the value of the UISegmentedControl. Here is the storyboard...
You can see that there is a base view with a UISegmentedControl, then there is a button on that same view that will trigger a switch of view controllers based on the state of the UISegmentedControl to one of the three view controllers on the right. I have included the class of my base UIViewController so that you all can see how I achieve the switching of views.
import UIKit
class RootViewController: UIViewController {
var nextViewIdentifier: String? = nil
@IBAction func switchViewButtonPressed(sender: UIButton) {
if (nextViewIdentifier != nil) {
let nextView = self.storyboard?.instantiateViewControllerWithIdentifier(nextViewIdentifier!) as! UIViewController
self.showViewController(nextView, sender: self)
}
}
@IBAction func valueChanged(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
nextViewIdentifier = "View1"
case 1:
nextViewIdentifier = "View2"
case 2:
nextViewIdentifier = "View3"
default:
nextViewIdentifier = nil
}
}
}
So, the first function switchViewButtonPressed
is called when the button is pressed and it will switch the view based on the variable nextViewIdentifier
. The second function valueChanged
simply changes the nextViewIdentifier
variable when a button on UISegmentedControl is pushed.
All of this code works, but it doesn't seem like a natural way to implement this in a storyboard format. It would seem like there should be something else to achieve the effect that I am looking for. I am asking if anyone has a better way to change views based on data that is not previously known in advance and when these views are completely different. Another way that I assume that I could do this is by just stacking different views in one view controller and then picking the one that I want through a prepareForSegue
method. Anyway, any suggestions about what is the best way to switch view controllers in this context is appreciated. Thanks.
In case anyone cares, the way that I solved this problems was by creating segues from main view controller itself and naming the segues with an identifier. Then, based on the position of the UISegmentedControl I called the segue with the identifier with the method self.performSegueWithIdentifier(<String Identifier>, sender: self)
.