Im attempting add image views to a UIView using this code:
for (int i = 0; i <numberOfImages; i++) {
UIImageView *image = [UIImageView alloc]initWithFrame:CGRectMake(40, 40, 40, 40)];
image.image = [images objectAtIndex:i];
[self.view addSubview:image];
}
This works but the problem is I would like to have a 5 second delay before it adds each image, instead it adds them all at the same time. Can anybody help me out? Thanks.
Example:
5 seconds = one image on screen
10 seconds = two images on screen
15 seconds = three images on screen
I think you'd be better off with an animation
Not exactly what you asked for, since all the views will be added immediately, and then faded-in, but I feel that you're actually trying to achieve that, like some sort of stacking of images, right?
In fact, if you plan on removing the previous image, you can do it in the completion block, like this:
also this is best option. Try this
Separate your code into a function, and call via
NSTimer
.And then your function:
userInfo
is a convenient way of passing parameters to functions that you need to call (but they do have to be Objects). Also, by usingrepeats:NO
, you don't have to worry about invalidating the timer, and there's no risk of leaving timer running in memory.You can use dispatch_after to dispatch a block, executed asynchronously that adds the image. Example:
It will be more efficient to use an NSTimer.
This will essentially call
methodToAddImages
repeatedly with the specified time interval. To stop this method from being called, call[NSTimer invalidate]
(bear in mind that an invalidated timer cannot be reused, and you will need to create a new timer object in case you want to repeat this process).Inside
methodToAddImages
you should have code to go over the array and add the images. You can use a counter variable to track the index.Another option (my recommendation) is to have a mutable copy of this array and add
lastObject
as a subview and then remove it from the mutable copy of your array.You can do this by first making a mutableCopy in reversed order as shown:
Your methodToAddImages looks like:
I don't know if you're using ARC or Manual Retain Release, but this answer is written assuming ARC (based on the code in your question).