利用SegmentedControl切换控制器的view

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了利用SegmentedControl切换控制器的view相关的知识,希望对你有一定的参考价值。

#import "ViewController.h"

#import "OneViewController.h"

#import "TwoViewController.h"

 

@interface ViewController ()

@property (nonatomic, strong) UISegmentedControl *segmentedControl;

@property (nonatomic, strong) UIViewController *currentViewController;

@end

 @implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

  self.segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"第一个视图",@"第二视图"]];

    self.segmentedControl.frame = CGRectMake(0, 0, 150, 30);

    self.navigationItem.titleView = self.segmentedControl;

    [self.segmentedControl addTarget:self action:@selector(segmentedControl:) forControlEvents:UIControlEventValueChanged];

    _segmentedControl.selectedSegmentIndex = 0;

    

    OneViewController *oneVC = [[OneViewController alloc] init];

    [self addChildViewController:oneVC];

    

    TwoViewController *twoVC = [[TwoViewController alloc] init];

    [self addChildViewController:twoVC];

    

    [self setSelectController:0];

}

 

- (void)segmentedControl:(UISegmentedControl*)scc{

    

    [self setSelectController:scc.selectedSegmentIndex];

}

 

- (void)setSelectController:(NSInteger)index{

    UIViewController *vc = [self.childViewControllers objectAtIndex:index];

    if (vc == self.currentViewController) {

        return;

    }

    [self.currentViewController.view removeFromSuperview];

    vc.view.frame = CGRectMake(0, 0, 320, 200);

    [self.view addSubview:vc.view];

     _currentViewController = vc;

}

以上是关于利用SegmentedControl切换控制器的view的主要内容,如果未能解决你的问题,请参考以下文章

Swift - 分段控制 - 切换多个视图

固定分段控制的水平位置

如何利用Vue.js库中的v-show显示和隐藏元素

SegmentedControl 未检测到更改

Swift 自定义分段控件 SegmentedControl

有没有办法让 SegmentedControl 一旦被选中就可以再次点击 - iOS