如何在循环中添加延迟? [英] How to add a delay to a loop?
问题描述
我正在尝试使用以下代码将图像视图添加到UIView:
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];
}
这可行,但是问题是我希望在添加每个图像之前有5秒的延迟,而是同时添加所有图像.有人可以帮我吗?谢谢.
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.
示例:
5 seconds = one image on screen
10 seconds = two images on screen
15 seconds = three images on screen
推荐答案
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).
在methodToAddImages
内,您应该具有遍历数组并添加图像的代码.
您可以使用计数器变量来跟踪索引.
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.
另一个选择(我的建议)是拥有该数组的可变副本,并将lastObject
作为子视图添加,然后将其从数组的可变副本中删除.
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.
您可以通过首先以相反的顺序制作mutableCopy来做到这一点,如下所示:
You can do this by first making a mutableCopy in reversed order as shown:
NSMutableArray* reversedImages = [[[images reverseObjectEnumerator] allObjects] mutableCopy];
您的methodToAddImages如下:
Your methodToAddImages looks like:
- (void)methodToAddImages
{
if([reversedImages lastObject] == nil)
{
[timer invalidate];
return;
}
UIImageView *imageView = [[UIImageView alloc] initWithFrame:(CGRectMake(40, 40, 40, 40))];
imageView.image = [reversedImages lastObject];
[self.view addSubview:imageView];
[reversedImages removeObject:[reversedImages lastObject]];
}
我不知道您使用的是ARC还是手动保留版本,但是此答案是在ARC(基于您问题中的代码)的前提下编写的.
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).
这篇关于如何在循环中添加延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!