[英]Adding a UIImage to UIImageView programmatically
在.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)來完成此操作。 有人可以幫我修改代碼,以便我只能通過代碼執行此操作嗎?
我認為你在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];
我從Interface構建器連接了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];
您需要使用框架,直到位置正確。 請注意,默認情況下,框架將自動與圖像大小相同。
你不需要連接。 此代碼無需連接即可運行。 離開IBOutlet。
UIImage *someImage = [UIImage imageName:@"http://image.com/image.jpg"];
UIImageView* imageView = [[UIImageView alloc] initWithImage:someImage];
[self.view addSubView:imageView];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.