jxdwinter
jxdwinter

Reputation: 2369

UIView addSubview and the subview isn't displayed

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    HeadViewController *headViewController = [[HeadViewController alloc] initWithNibName:@"HeadViewController" bundle:nil];    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 120)];
    [view addSubview:headViewController.vew];
    [self.view addSubview:view];
}

HeadViewController.h:

@interface HeadViewController : UIViewController
{
    IBOutlet UIView *view;
}
@property (nonatomic, retain)IBOutlet UIView *view;
@end

and I connect the view to the file's owner.

And I can't see the headViewController.view.

Upvotes: 7

Views: 31329

Answers (3)

Bharath
Bharath

Reputation: 180

i is missing in the syntax

[view addSubview:headViewController.view];

Upvotes: 0

Daniel Ford
Daniel Ford

Reputation: 59

It looks like a typo - forgot the i in .view

[view addSubview:headViewController.vew];

Upvotes: 0

marzapower
marzapower

Reputation: 5611

First of all, you do not need to define the view outlet in the HeadViewController class. It is automatically inherited from the UIViewController super class.

Then, I suggest you to add directly the view of HeadViewController to your current view. Eg.

- (void)viewDidLoad
{
     [super viewDidLoad];
     // Do any additional setup after loading the view from its nib.
     HeadViewController *headViewController = [[HeadViewController alloc] initWithNibName:@"HeadViewController" bundle:nil];    
     headViewController.view.frame = CGRectMake(0, 0, 320, 120);
     [self.view addSubview:headViewController.view];
}

But, if you are using ARC (Automatic Reference Counting), the headViewController instance will probably be deallocated after the end of the viewDidLoad method. It is convenient (and I'd say it is compulsory) to assign that instance to a local variable in the controller you are currently displaying. This way you will be able to handle its view's components later if needed, the instance will be retained, and everything else will work perfectly. You should have something like:

- (void)viewDidLoad
{
     [super viewDidLoad];
     // Do any additional setup after loading the view from its nib.
     self.headViewController = [[HeadViewController alloc] initWithNibName:@"HeadViewController" bundle:nil];    
     headViewController.view.frame = CGRectMake(0, 0, 320, 120);
     [self.view addSubview:headViewController.view];
}

and

@interface MyController ()
    @property (nonatomic, strong) HeadViewController *headViewController;
@end

in the hidden interface definition at the beginning of the .m class implementation file.

Upvotes: 15

Related Questions