Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Add multiple UIImageViews programmatically in runtime

So, I'm doing a Breakout-clone on the iPhone. All elements except the bricks to hit, are created and working as expected with the NIB-file.

However, if I want to create different levels and run collision detection on the bricks, it seems stupid to add them in Interface Builder. How do I add them to the view in code?

I got an image called "brick.png" that I want to use with an UIImageView. Also, I want to have arrays and / or lists with these so I can build cool levels with pattern in the bricks and all :)

How do I do this in code?

like image 252
Emil Avatar asked Sep 19 '11 04:09

Emil


2 Answers

@Mark is right, I would just add where the image need to be displayed!

UIImageView *imgView = [[[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 20)] autorelease];
NSString *imgFilepath = [[NSBundle mainBundle] pathForResource:@"brick" ofType:@"png"];
UIImage *img = [[UIImage alloc] initWithContentsOfFile:imgFilepath];
[imgView setImage:img];
[img release];
[self.view addSubview:imgView];

I tested the code and for me only shows when told the coordinates

like image 176
manuelBetancurt Avatar answered Sep 23 '22 15:09

manuelBetancurt


It's really pretty easy. Here's an example of how you would create and display a UIImageView programatically...

UIImageView *imgView = [[[UIImageView alloc] init] autorelease];
NSString *imgFilepath = [[NSBundle mainBundle] pathForResource:@"brick" ofType:@"png"];
UIImage *img = [[UIImage alloc] initWithContentsOfFile:imgFilePath];
[imgView setImage:img];
[img release];
[self.view addSubview:imgView];

That's pretty much all there is to it.

like image 45
Mark Armstrong Avatar answered Sep 22 '22 15:09

Mark Armstrong