Question

I'm trying to load a background image programmatically but image is not displaying. Here is my code:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"];
        UIImage *backGroundImage = [UIImage imageWithContentsOfFile:filePath];
        self.backGroundView = [[UIImageView alloc] initWithImage:backGroundImage];
        self.backGroundView.hidden = NO;

    }
    return self;
}

If print the console the UIImageView:

po _backGroundView
<UIImageView: 0x15d40cf0; frame = (0 0; 568 320); opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x15d41fb0>>

Any of you knows why the image is not loading on the screen?

Was it helpful?

Solution

You are overwriting the existing backgroundView with a new one - just set the image on the existing one (created automatically when the nib is loaded).

self.backGroundView.image = backGroundImage;

The way the code is at the moment, you replace the nib-created view with a new one, which isn't then added to the viewController.view. It doesn't show up - the existing view will still be there, in the view hierarchy - but won't be attached to the property - so the image change won't affect it...

OTHER TIPS

You need to remove the code related to self.backGroundView from initWithNibName:bundle: and add it to viewDidLoad:

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"];
    UIImage *backGroundImage = [UIImage imageWithContentsOfFile:filePath];
    self.backGroundView = [[UIImageView alloc] initWithImage:backGroundImage];
    self.backGroundView.hidden = NO;
    [self.view addSubview:self.backGroundView];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top