UIImageView alloc] initWithImage使用IBOutlet无法正常工作

时间:2012-01-24 21:00:50

标签: iphone uiimageview

我通常遵循在我的方法中创建对象的模式(如viewDidLoad),将属性保留在其上,然后释放创建的原始对象。所以像这样:

NSArray *myArray = [NSArray alloc] initWithObjects:@"1", @"2", @"3", nil];
self.array = myArray;
[myArray release];

我以为我可以用UIImageView做同样的事情。我在UIImageView创建了.xib。我有一个出口,这是一个像这样的财产

@property (nonatomic, retain) IBOutlet UIImageView *imageView;

在我的viewDidLoad中,我这样做:

UIImageView *imgView = [[UIImageView alloc] initWithImage;[UIImage imageNamed:@"arrow.png"]];
self.imageView = imgView;
[imgView release];

如果我运行这个,我在屏幕上看不到任何内容。但是,如果我在我的viewDidLoad中改为:

[self.imageView setImage:[UIImage imageNamed:@"arrow.png"]];

我确实在屏幕上显示了我的箭头图像。我在这里遗失的UIImageView有什么不同吗?

由于第一次回复而导致编辑:UIImageViewUITableView不同,因为我需要将其作为子视图添加到当前视图中吗?当我在UITableView中创建IB时,我不会在subview中将其添加为viewDidLoad

感谢。

2 个答案:

答案 0 :(得分:5)

你错过了IBOutlet如何运作的重点。如果在.xib中指定了某些内容,那么它已经为您分配了:)您只需使用它。

因此,[self.imageView setImage:[UIImage imageNamed:@"arrow.png"]];可用,因为您刚刚为其分配了图像。

然而,在做的时候

UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"arrow.png"]];
self.imageView = imgView;
[imgView release];

您实际取消了imageViewIB创建的self.imageView = imgView;实例并设置了新实例,并且您都没有将其作为子视图添加到任何内容中。因为它是一个新的实例,所以需要添加!!但无论如何,如果您使用IBOutlet

,这种方法是错误的

答案 1 :(得分:0)

您需要将self.imageView添加到视图层次结构中。

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.imageView = ...

    // You are missing this part!
    [self.view addSubview:self.imageView];

    ...
}

PS。您不需要将UIImageView属性标记为IBOutlet,因为您没有使用Interface Builder来构建视图。