Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView addSubview and the subview isn't displayed

Tags:

ios

uiview

- (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.

like image 454
jxdwinter Avatar asked Mar 29 '12 06:03

jxdwinter


1 Answers

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.

like image 151
marzapower Avatar answered Oct 24 '22 10:10

marzapower