我创建了一个包含以下内容的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")
}
它从内存中获取一个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)
})
}
答案 0 :(得分:2)
更改所选索引后,只需调用函数self.segmentController(mySegmentControl)
。