Jigen Jigen - 5 months ago 49
Swift Question

UISegmentedControl programmatically

I have created a ViewController that contains:


  • UISegmentedControl

  • Container



Image1

I'm trying to change the selection programmatically when I arrive from another view.
I tried with:

if let previousSelection = NSUserDefaults.standardUserDefaults().stringForKey("SEGMENT_CONTROL") {
segmentSaved = Int(previousSelection)!
}

if (segmentSaved == 0) {
mySegmentControl.selectedSegmentIndex = segmentSaved
} else if (segmentSaved == 1) {
mySegmentControl.selectedSegmentIndex = segmentSaved
} else if (segmentSaved == 2) {
mySegmentControl.selectedSegmentIndex = segmentSaved
} else {
print("Error")
}


It takes an int from memory and use it as index of the UISegmentedControl. It works but doesn't change the view in the container.

How can I do to change the container?

This is how it works:

let viewControllerIdentifiers = ["ViewController1", "ViewController2", "ViewController3"]

@IBAction func segmentController(sender: UISegmentedControl) {

let newController = (storyboard?.instantiateViewControllerWithIdentifier(viewControllerIdentifiers[sender.selectedSegmentIndex]))! as UIViewController
let oldController = childViewControllers.last! as UIViewController

oldController.willMoveToParentViewController(nil)
addChildViewController(newController)
newController.view.frame = oldController.view.frame

transitionFromViewController(oldController, toViewController: newController, duration: 0.25, options: .TransitionCrossDissolve, animations:{ () -> Void in
}, completion: { (finished) -> Void in
oldController.removeFromParentViewController()
newController.didMoveToParentViewController(self)

})


}

Answer

Just call function self.segmentController(mySegmentControl) after you change the selected index.