以编程方式向UIImageView添加UIImage

时间:2011-12-15 16:35:27

标签: iphone objective-c

在.h文件中我声明了这个;

IBOutlet UIImageView *image;

在.m文件中;

UIImage *image1 = [UIImage imageName:@"http://image.com/image.jpg"];
image = [[UIImageView alloc] initWithImage:image1];
image.frame = CGRectMake(0,0, 50,50);
[self.view addSubView:image];

我从Interface构建器连接了UIImageView。但我需要通过代码(不使用Interface Builder)来完成此操作。有人可以帮我修改代码,这样我只能通过代码来完成吗?

4 个答案:

答案 0 :(得分:7)

我认为你在uiimageview中显示远程图像有一些问题所以我应该这样做。

NSData *receivedData = [[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://image.com/image.jpg"]] retain];
UIImage *image = [[UIImage alloc] initWithData:receivedData] ;

UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0,0, 50,50);
[self.view addSubView:image];

[image release];
[imageView release];

答案 1 :(得分:3)

  

我连接了界面构建器

中的UIImageView

这是一个错误。如果这样做,image实例变量指向的图像视图将是错误的 - 笔尖中的图像视图。您希望它是您在代码中创建的那个。

因此,不要使用Interface Builder建立连接;实际上,从Interface Builder中删除图像视图,这样就不会让自己感到困惑。确保您的实例变量也是属性:

@property (nonatomic, retain) UIImageView* image;

合成属性:

@synthesize image;

现在您的代码将起作用:

UIImage *image1 = [UIImage imageName:@"http://image.com/image.jpg"];
self.image = [[UIImageView alloc] initWithImage:image1];
// no memory management needed if you're using ARC
[self.view addSubview:self.image];

您需要使用框架,直到位置正确。请注意,默认情况下,框架将自动与图像大小相同。

答案 2 :(得分:2)

你不需要连接。此代码无需连接即可运行。将IBOutlet留下。

答案 3 :(得分:2)

UIImage *someImage = [UIImage imageName:@"http://image.com/image.jpg"];
UIImageView* imageView = [[UIImageView alloc] initWithImage:someImage];
[self.view addSubView:imageView];