ios - UISegmentedControl 以编程方式

标签 ios swift uiview uiviewcontroller uisegmentedcontrol

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

  • UISegmentedControl
  • 容器

Image1

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

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 的索引。它可以工作,但不会更改容器中的 View 。

如何更改容器?

它是这样工作的:

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)

关于ios - UISegmentedControl 以编程方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37813129/

相关文章:

swift - 从条件解析中获取数据

swift - Swift 3 中的 NSFetchedResultsController deleteCache

SwiftUI macOS View 在显示多个图表时开始滞后

ios - 在 UILocalNotification 触发后修改它的最佳方法是什么?

ios - 如何在表格单元格中自动更改标签的大小?

ios - 在不使用自动布局的情况下为 3.5 英寸和 4 英寸 iPhone 屏幕自定义布局

iphone - 从 nib 加载自定义 UIView,nib 中包含的所有 subview 都是零?

ios - 如何检查 UIView 的背景颜色是否为 clearColor?

ios - 所需条件为假 : IsFormatSampleRateAndChannelCountValid(hwFormat)

ios - iPhone CGContext : drawing line with two different colors