2011-12-15 110 views
2

在.h文件中我聲明瞭這一點;以編程方式向UIImageView添加UIImage

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]; 

和我連接從接口生成器的UIImageView。但我需要這樣做只能通過代碼(不使用Interface Builder)。有人可以幫助我修改代碼,以便我只能通過代碼來完成此操作嗎?

回答

2

你不需要連接。此代碼將無需連接即可使用。離開IBOutlet。

+0

你說我需要刪除`IBOutlet`並從Interface Builder中刪除`UIImageView`,代碼將工作? – Illep 2011-12-15 16:47:09

+0

是的。你有你需要的一切:你創建一個imageView,設置圖像,設置框架並將其添加到視圖。 – Chakalaka 2011-12-15 16:55:59

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

您還沒有指定UIImageView的大小,以便圖像佔用整個幀? – Illep 2011-12-15 16:49:18

+0

它會自動將其設置爲您正在啓動的圖像'someImage'的大小。 – 2011-12-16 03:42:06

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]; 
3

和我連接從界面生成器

這是一個錯誤的的UIImageView。如果你這樣做,你的image實例變量所指向的圖像視圖將是錯誤的 - 即筆尖中的一個。你希望它是你在代碼中創建的那個。

因此,不要從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]; 

您將需要與框架,直到打該位置是正確的。請注意,默認情況下,該框架將自動與圖像大小相同。

相關問題