无法在第一个视图控制器的顶部嵌入第二个视图控制器

时间:2016-11-25 13:06:51

标签: ios

我使用以下代码在第二个视图控制器的顶部显示第一个视图控制器,就像对话框一样。

    [self addChildViewController:viewController];
viewController.view.frame = self.view.frame;
[self.view addSubview:viewController.view];
viewController.view.alpha = 0;
[viewController didMoveToParentViewController:self];

[UIView animateWithDuration:0.25 delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^
 {
     viewController.view.alpha = 1;
 }
                 completion:nil];

但第二个视图控制器不可见......我怎样才能对此进行排序?

2 个答案:

答案 0 :(得分:1)

  1. 尝试[parentView bringSubviewToFront:childView];

  2. 尝试viewController.view.frame = self.view.bounds;

  3. 请检查您是否已正确实例化viewController

答案 1 :(得分:1)

必须有错误代码的地方,我已经为此编写了一个演示: 我写了两个像这样的控制器:

vc1

#import "ViewController.h"
#import "ViewController2.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initUI];
}

#pragma mark - init

- (void)initUI {

self.view.backgroundColor = [UIColor whiteColor];

A) If use storyboard, init vc2 like this :
 UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
 ViewController2 *vc2 = [sb instantiateViewControllerWithIdentifier:@"ViewController2"];

B)If use code ,init vc2 like this:
ViewController2 *vc2 = [[ViewController2 alloc] init];


[self addChildViewController:vc2];
vc2.view.frame = self.view.bounds
[self.view addSubview:vc2.view];
vc2.view.alpha = 0;
[vc2 didMoveToParentViewController:self];

[UIView animateWithDuration:0.25 delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^
     {
         vc2.view.alpha = 1;
     }
                 completion:nil];
}

@end

vc2

#import "ViewController2.h"

@interface ViewController2 ()

@end

@implementation ViewController2

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

    self.view.backgroundColor = [UIColor brownColor];

}