Jigen Jigen - 1 year ago 234
Swift Question

UISegmentedControl programmatically

I have created a ViewController that contains:

  • UISegmentedControl

  • Container


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 {

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

newController.view.frame = oldController.view.frame

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



Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download