如何为循环添加延迟? [英] How to add a delay to a loop?

查看:26
本文介绍了如何为循环添加延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此代码将图像视图添加到 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

推荐答案

使用 NSTimer.

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:numberOfSeconds
                                                      target:self 
                                                    selector:@selector(methodToAddImages:) 
                                                    userInfo:nil 
                                                     repeats:YES];

这实际上会以指定的时间间隔重复调用 methodToAddImages.要停止调用此方法,请调用 [NSTimer invalidate](请记住,无效的计时器无法重复使用,并且您需要创建一个新的计时器对象以防重复此过程).

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 还是 Manual Retain Release,但这个答案是假设 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆