在UIImageView中加载图像的iOS未显示

时间:2014-04-29 18:16:11

标签: ios uiimageview

我正在尝试以编程方式加载背景图像,但图像未显示。这是我的代码:

- (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;
}

如果打印控制台UIImageView:

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

你们中的任何人都知道为什么图片没有加载到屏幕上?

2 个答案:

答案 0 :(得分:3)

您正在用新的覆盖现有的backgroundView - 只需将图像设置为现有的(在加载笔尖时自动创建)。

self.backGroundView.image = backGroundImage;

目前代码的方式是,用新的视图替换nib创建的视图,然后将其添加到viewController.view中。它没有显示 - 现有视图仍然存在于视图层次结构中 - 但不会附加到属性 - 因此图像更改不会影响它...

答案 1 :(得分:0)

您需要从self.backGroundView中删除与initWithNibName:bundle:相关的代码,并将其添加到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];
}