UISegmentedControl 以编程方式

UISegmentedControl programmatically

我创建了一个 ViewController,其中包含:

当我从另一个视图到达时,我正在尝试以编程方式更改选择。 我试过:

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")
    }

它从内存中获取一个整数并将其用作 UISegmentedControl 的索引。它可以工作,但不会更改容器中的视图。

如何更改容器?

它是这样工作的:

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)