我有一个属性的视图应该从我的视图控制器获取NSString并显示图像。如果我在视图中使用“320x213-1.png”对locationImageFile进行硬编码,则图像显示正常,但如果我尝试从视图控制器设置locationImageFile,则不会显示图像。我觉得我错过了一些非常基本的东西。旁注:我似乎能够从我的视图控制器中设置locationTitle属性而没有任何问题。
LocationViewController.m
#import "LocationViewController.h"
#import "LocationView.h"
@implementation LocationViewController
{
LocationView *_locationView;
}
- (void)loadView
{
CGRect frame = [[UIScreen mainScreen] bounds];
_locationView = [[LocationView alloc] initWithFrame:frame];
[self setView:_locationView];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
_locationView.locationTitle.text = aLocation.name;
_locationView.locationImageFile = @"320x213-1.png";
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
LocationView.m
#import "LocationView.h"
@implementation LocationView
@synthesize locationTitle;
@synthesize locationImageFile;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
[self setBackgroundColor: [UIColor blueColor]];
// Image container
UIImage *locationImage = [UIImage imageNamed:locationImageFile];
UIImageView *locationImageContainer = [[UIImageView alloc] initWithImage:locationImage];
[locationImageContainer setTranslatesAutoresizingMaskIntoConstraints:NO];
locationImageContainer.backgroundColor = [UIColor yellowColor];
[self addSubview:locationImageContainer];
// Text line
locationTitle = [[UILabel alloc]init];
[locationTitle setTranslatesAutoresizingMaskIntoConstraints:NO];
locationTitle.backgroundColor = [UIColor whiteColor];
[self addSubview:locationTitle];
}
return self;
}
@end
答案 0 :(得分:1)
初始化LocationView
时,实例变量locationImageFile
的值等于nil
。覆盖locationImageFile
内的LocationView.m
属性的setter,如下所示:
- (void)setLocationImageFile:(NSString *)aLocationImageFile
{
locationImageFile = aLocationImageFile;
locationImageContainer.image = [UIImage imageNamed:aLocationImageFile];
}
答案 1 :(得分:1)
我认为这是因为loadView
方法比viewDidLoad
方法更早调用。
因此,当您设置_locationView.locationImageFile = @"320x213-1.png";
时,未设置containerView的图像。
您可以考虑将locationImageContainer
声明为locationView的属性,并直接设置它的图像。赞。
_locationView.locationImageContainer.image = [UIImage imageNamed:@"320x213-1.png"];
而不是将locationImageFile设置为属性。
答案 2 :(得分:0)
您可以尝试这样做:
_locationView.locationImageFile = [UIImage imageNamed:locationImageFile];
如果你这样做:
_locationView.locationImageFile = locationImageFile;