user31231234124 user31231234124 - 7 days ago 6
iOS Question

Unable to embed second view controller on top of first view controller

Im using the following code to show first view controller on top of a second view controller just like a dialog.

[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];


But the second view controller is not visible...How can I be able to sort this out?

Answer

There must be where you mistake the code, I have write a demo for that: I write two controller like this:

In 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

In 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];

}
Comments