Swift:延迟增加标签

编程入门 行业动态 更新时间:2024-10-27 13:32:09
本文介绍了Swift:延迟增加标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

当我的应用程序到达这部分代码时,它会冻结.我试图以半秒的延迟增加一个数字,然后将其打印到屏幕上.所以标签文本会变成 1,然后是 2,然后是 3,等等.我把这段代码扔到了操场上,DispatchQueue 似乎无限上升.谢谢.

My app freezes when it reaches this part of the code. I am attempting to increment a number with a half of a second delay, then printing that to the screen. So the label text would turn into a 1, then a 2, then a 3, etc. I threw this code into playground and the DispatchQueue seems to infinitely go up. Thanks.

var percentage = 0

func incrementLabel (amount: Int){
    var count = 0
    while count <= amount{
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
            percentage += 1
            count += 1
        })
    }
}

incrementLabel(amount: 10)
print(percentage)

推荐答案

这里有一个替代解决方案,您可以使用它来代替 DispatchQueue:

Here is an alternative solution that you could use instead of DispatchQueue:

var percentage = 0
var counter = 0
var timer: Timer?

func incrementLabel(amount: Int) {
    counter = amount
    timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(self.updateDelay), userInfo: nil, repeats: true)
}

@objc func updateDelay() {
    if (counter > 0) {
        counter -= 1

        percentage += 1
    } else {
        timer.invalidate()
        timer = nil
    }
}

incrementLabel(amount: 10)
print(percentage)

这在 Swift 中使用了 Timer.

This uses Timer in Swift.

这篇关于Swift:延迟增加标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

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

发布评论

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

>www.elefans.com

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