Emil
Emil

Reputation: 1045

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?

Upvotes: 5

Views: 10892

Answers (2)

manuelBetancurt
manuelBetancurt

Reputation: 16138

@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

Upvotes: 8

Mark Armstrong
Mark Armstrong

Reputation: 839

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.

Upvotes: 1

Related Questions