如何为循环添加延迟?

编程入门 行业动态 更新时间:2024-10-27 16:28:17
本文介绍了如何为循环添加延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

如何为循环添加延迟?

本文发布于:2023-11-29 19:13:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647367.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:何为

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!