Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

ios - How to display multiple UIImageViews

I have 5 images I would like to display on the view randomly. My image names are as follows: image-0, image-1, image-2, image-3, image-4.

What I need is I want to display each image, but the problem is when I write the code to display a second, it stacks on top of the first image. Here is my code to display one of my images:

    - (void)viewDidLoad
{
int xValue = arc4random() % 320;
int yValue = arc4random() % 480;
image.center = CGPointMake(xValue, yValue);


{UIImageView *imgFive = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image-5.png"]];
[self.view addSubview:imgFive];
    imgFive.center = CGPointMake(xValue, yValue);}

But if I add the same code but instead of "image-5.png" I use the other file names to try and display them, they stack on top of eachother. My images are circles, each varying size. So when I try and display all 5 I can see my circles have stacked on top of eachother from smallest to largest.

What do I need to do to separate these images from eachother? Do I need to put these images in an array and then loop through the array to display them how I would like?

Any help is appreciated, I am very new to coding so a simple explanation would be helpful in explaining why your code works.

Thanks again!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Considering your requirement, and the general structure names provided to your images, i guess you need to just loop your logic .

for(int i=0;i<5;i++) {

    float xpos = arc4random() %320 ;
    float ypos = arc4random() %480 ;

    UIImage *image = 
     [UIImage imageNamed:[NSString stringWithFormat:@"image-%d.png",i]] ;

    UIImageView *imageView = 
     [[UIImageView alloc]initWithImage:image];

    imageView.center=CGPointMake(xpos, ypos);
    [self.view addSubview:imageView];          
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...