Jakub
Jakub

Reputation: 13860

Dynamiclly creating View in iOS

I have a project with one View. I'm drawing everything on it programically. So when i want to add another View (screen) to my project i create a class inherits from the UIViewController class and implements method

- (void)viewDidLoad

And then i want to load this View from my original View, and i do this:

In ViewController.h

#import <UIKit/UIKit.h>
#import "TestViewControllerClass.h"

@interface ViewController : UIViewController <UITableViewDataSource> {
}

@property (strong,nonatomic) TestViewControllerClass *testView;

@end

In ViewController.m

@implementation ViewController

@synthesize testView;

- (void)viewDidLoad
{
    [super viewDidLoad];

    testView = [[TestViewControllerClass alloc] init];
    [self.view addSubview:testView]; //crash here

}

And then in my TestViewControllerClass.h

#import <UIKit/UIKit.h>

@interface TestViewControllerClass : UIViewController

@end

And TestViewControllerClass.m

- (void)viewDidLoad
{
    [super viewDidLoad];
}

To check if method wiewDidLoad will be executed i put there a breakpoint, but nothing happend. In fact, my app crash (I put comment at code where).

When crashes i receive: -[TestViewControllerClass superview]: unrecognized selector sent to instance 0x683aca0

Upvotes: 0

Views: 277

Answers (4)

MJVDM
MJVDM

Reputation: 3963

What you're doing is settings your ViewController as the view, not the real view

testView = [[TestViewControllerClass alloc] init];
    [self.view addSubview:testView]; //crash here

this will obviously crash. Assuming you have a view variable declared in your header file called view, use

testView = [[TestViewControllerClass alloc] init];
     [self.view addSubview:testView.view];

Upvotes: 2

Dinesh
Dinesh

Reputation: 6532

You can load two types for uiviewcontroller loading below:

[self.view addSubview:testView.view];

(or)

use presentmodalviewcontroller below code:

    testView *popupView = [[testView alloc] initWithNibName:@"testView" bundle:nil];
    popupView.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentModalViewController:popupView animated:YES];

dimiss modal view cntroller below code:

[self dismissModalViewControllerAnimated:YES];

thanks..!

Upvotes: 0

Nitin
Nitin

Reputation: 7461

Use this code...

[self.view addSubview:testView.view];

Hope,this will help you...

Upvotes: 2

graver
graver

Reputation: 15213

Replace

[self.view addSubview:testView]; //crash here

with

[self.view addSubview:testView.view];

Upvotes: 3

Related Questions