killerwakka
killerwakka

Reputation: 31

How do I create a UIImageView using only code?

I am rather new to Cocoa programming and need some help.

I want to make some image views for units in a game and add them with code, because to put them in the view and make conections in Interface Builder is a lot of work.

I already have found code to create and insert UIImageViews:

UIImageView *image0 =[[UIImageView alloc] initWithFrame:CGRecMake(x,y,w,h)];
image0.image=[UIImage imageNamed:@"image.png"];
[self.view addSubview:image0];

My question is: if I can make an array, then I don't have to write this for every image view, and I put the same image in it?

Upvotes: 0

Views: 7746

Answers (2)

David Hoerl
David Hoerl

Reputation: 41622

How about this:

for(int i=0; i<10; ++i) {
    UIImageView *image =[[UIImageView alloc] initWithFrame:CGRecMake(x+i*k1,y*i*k2,w,h)];
    image.image=[UIImage imageNamed:@"image.png"];
    image.tag = i+1;
    [self.view addSubview:image0];
}

Upvotes: 1

Ryan Poolos
Ryan Poolos

Reputation: 18551

A nice way to do it would be something like this. This will create 30 image views with the same image.

NSMutableArray *arrayOfImageViews = [NSMutableArray array];
for (int i = 0; i < 30; i++) {
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"theImage.png"]];
    [self.view addSubview:imageView];

    [arrayOfImageViews addObject:imageView];
}

Upvotes: 1

Related Questions