简体   繁体   中英

How do I get the Segmented Control index from one view controller to another containerview controller in Swift iOS development?

我在命名为仪表板控制器的视图控制器之一中使用三个索引分段控件,并将segue传递到容器视图以在仪表板控制器中加载三个不同的视图控制器,但所选索引仍显示分段控件,但容器视图正在加载仪表板控制器下的默认第一视图控制器。

Here's how I do it.

  • Don't link the segmented control to a segue directly, but to an action in the dashboard controller .
  • Swap out the views from the dashboard controller.

func switchViews(_ sender: Any?) {
    // vcSelector is an instance variable, or you can use the sender
    let subVCIndex = vcSelector?.selectedSegmentIndex
    // also an instance variable
    currentViewController = nil
    switch subVCIndex {
        case 0:
            currentViewController = self.storyboard!.instantiateViewController(withIdentifier: "SubControllerA")
            // set up for case 0
        case 1:
            currentViewController = self.storyboard!.instantiateViewController(withIdentifier: "SubControllerB")
            // set up for case 1
        // ...
        default:
            // should never happen
            NSLog("*** Invalid view mode! ***")
            return // bail out
    }

    // add the new view controller
    self.addChildViewController(currentViewController!)

    // take out all the old subviews
    for subview in self.containerView!.subviews {
        subview.removeFromSuperview()
    }

    // install the new subVC's view
    self.containerView?.addSubview(currentViewController!.view)
    currentViewController!.view.frame = self.containerView!.bounds
}

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