UISegmentedControl以编程方式

时间:2016-06-14 13:14:10

标签: ios swift uiview uiviewcontroller uisegmentedcontrol

我创建了一个包含以下内容的ViewController:

  • UISegmentedControl
  • 容器

Image1

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

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

它从内存中获取一个int并将其用作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)

    })


}

1 个答案:

答案 0 :(得分:2)

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