答案 0 :(得分:2)
按照以下步骤操作。
添加VC1& VC2作为mainVC的childVC。
在第1段选择VC1.view.hidden = false
& vc2.view.hidden = true
在第2段选择VC2.view.hidden = false
& vc1.view.hidden = true
参考
代码工作
@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中为每个标签使用容器视图。这样,与每个视图相关的逻辑在不同的视图控制器中分离。你可以这样做:
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;
}
}