Search code examples
iosuiviewuiimageviewaddsubview

adding UIView to view with a UIImageView parameter


I can't figure out what's wrong with this. I am trying to add a sub view to my current view. I alloc and initWithNibName my SecondViewController and set its myImageView parameter that is a UIImageView. The problem is that when the subView is added the myImageView is not set.

This is the code:

- (void)viewDidLoad
{
   [super viewDidLoad];
SecondViewController *secondView = [[SecondViewController alloc]initWithNibName:@"SecondViewController" bundle:nil];

secondView.myImageView.image = [UIImage imageNamed:@"image1.png"];

[self.view addSubview secondView.view];
}

if I set an image to myImageView via Interface Builder it is correctly displayed on addSubview but if I set the property as described above it doesn't work... The UIImageViewoutlet is correctly connected on IB.

this is the SecondViewController :

@interface SecondViewController : UIViewController
{

}

@property(nonatomic,strong)IBOutlet UIImageView *myImageView;


@end

Solution

  • I believe your problem is that when you call secondView.myImageView.image = [UIImage imageNamed:@"image1.png"]; the myImageView outlet has not yet been set. The documentation for initWithNibName:bundle: says, "The nib file you specify is not loaded right away. It is loaded the first time the view controller’s view is accessed." So you need code like this:

    - (void)viewDidLoad
    {
       [super viewDidLoad];
    SecondViewController *secondView = [[SecondViewController alloc]initWithNibName:@"SecondViewController" bundle:nil];
    
    // Force the nib to load, which subsequently sets the myImageView outlet
    [secondView view];
    
    secondView.myImageView.image = [UIImage imageNamed:@"image1.png"];
    
    [self.view addSubview secondView.view];
    }
    

    However, I don't recommend this approach. You should really set the image of the myImageView outlet in SecondViewController's -viewDidLoad method. That's where it belongs.

    // SecondViewController.m
    
    - (void)viewDidLoad
    {
         [super viewDidLoad];
    
         self.myImageView.image = [UIImage imageNamed:@"image1.png"];
    }
    

    And then in the other view controller's -viewDidLoad method, just add SecondViewController's view as a subview like before:

    - (void)viewDidLoad
    {
         [super viewDidLoad];
    
         SecondViewController *secondVC = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
    
         [self.view addSubview:secondVC.view];
    }