切换子viewController使用分段控件

时间:2017-04-20 07:02:45

标签: ios uiviewcontroller storyboard

我想从分段控件中切换子视图控制器。

故事板中有vc1和vc2,主vc的导航控制器栏上有段控制。

我想在主vc上添加vc1和vc2,如何使用段控制器切换子vc?

enter image description here

怎么办?

3 个答案:

答案 0 :(得分:2)

按照以下步骤操作。

  1. 添加VC1& VC2作为mainVC的childVC。

  2. 在第1段选择VC1.view.hidden = false& vc2.view.hidden = true

  3. 在第2段选择VC2.view.hidden = false& vc1.view.hidden = true

  4. 参考

    1. How-to-add-childVC

    2. How-tobind-segment-control-action

    3. 代码工作

      @IBAction func indexChanged(_ sender: AnyObject) {
          switch segmentedControl.selectedSegmentIndex
          {
          case 0:
              vc1.view.hidden = false
              vc2.view.hidden = true
          case 1:
              vc2.view.hidden = false
              vc1.view.hidden = true
          default:
              break
          }
      }
      

答案 1 :(得分:1)

接受的答案显然是正确的,但老实说,我更喜欢在UISegmentedControl中为每个标签使用容器视图。这样,与每个视图相关的逻辑在不同的视图控制器中分离。你可以这样做:

enter image description here

class TopViewController: UIViewController {

    @IBOutlet weak var firstContainerView: UIView!
    @IBOutlet weak var secondContainerView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        firstContainerView.alpha = 1.0
        secondContainerView.alpha = 0.0
    }

    @IBAction func didChangeIndex(_ sender: UISegmentedControl) {
        switch sender.selectedSegmentIndex {
        case 0:
            firstContainerView.alpha = 1.0
            secondContainerView.alpha = 0.0
        case 1:
            firstContainerView.alpha = 0.0
            secondContainerView.alpha = 1.0
        default:
            break
        }
    }
}

如果您想访问FirstViewController或SecondViewController的属性,可以实现prepare(for segue: UIStoryboardSegue, sender: Any?)方法。

答案 2 :(得分:0)

您应该将vc和vc.view添加到Main ViewController:

当您选择分段控件时,您可以隐藏子视图控制器的视图,如下所示:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    _vc1 = [sb instantiateViewControllerWithIdentifier:@"ViewController1"];
    _vc2 = [sb instantiateViewControllerWithIdentifier:@"ViewController2"];

    [self addChildViewController:_vc1];
    [self addChildViewController:_vc2];
    [self.view addSubview:_vc1.view];
    [self.view addSubview:_vc2.view];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)segAction:(UISegmentedControl *)sender {

    if (1 == sender.selectedSegmentIndex) {
        NSLog(@"1");

        _vc1.view.hidden = YES;
        _vc2.view.hidden = NO;
    }else {
        NSLog(@"%ld", sender.selectedSegmentIndex);
        _vc2.view.hidden = YES;
        _vc1.view.hidden = NO;
    }

}