简体   繁体   中英

Adding a UIImage to UIImageView programmatically

In .h file I declare this;

IBOutlet UIImageView *image;

In .m file;

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

and I connected the UIImageView from the Interface builder. But I need to do this Only by code (without using the Interface Builder). Can someone help me modify the code so that I could do this only by code?

I THINK you have some problem in displaying a remote image in uiimageview so i thing u should do that fashion.

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

and i connected the UIImageView from the Interface builder

That was a mistake. If you do that, the image view pointed to by your image instance variable will be the wrong one - the one in the nib. You want it to be the one that you created in code.

So, make no connection from Interface Builder; in fact, delete the image view from Interface Builder so you don't confuse yourself. Make sure your instance variable is also a property:

@property (nonatomic, retain) UIImageView* image;

Synthesize the property:

@synthesize image;

Now your code will work:

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

You will need to play with the frame until the location is correct. Note that the frame will automatically be the same size as the image, by default.

you dont need to connect. This code will work without connecting. Leave IBOutlet out.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM