简体   繁体   中英

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 {
        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)

    })


}

更改所选索引后,只需调用self.segmentController(mySegmentControl)函数self.segmentController(mySegmentControl)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM