You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何临时暂停函数执行以实现逐帧切换Emoji的动画效果?

iOS Emoji逐个切换动画实现方案

你的代码看不到切换过程的核心原因是:同步循环会让主线程连续执行所有UI更新,系统会把这些更新合并,最终只显示最后一次的结果。而且绝对不能用类似wait(1)的阻塞方法——这会卡死主线程,导致整个APP失去响应。

下面是两种可行的实现方式:

方案一:递归+延迟执行

通过递归配合DispatchQueue.asyncAfter,每次切换后延迟一段时间再执行下一次,给主线程留出更新UI的时间:

func pickingAnimation() {
    let totalSwitches = 10
    func switchNext(count: Int) {
        guard count < totalSwitches else { return }
        currentEmoji.text = randomEmoji().rawValue
        // 调整延迟时间(比如0.1秒)控制切换速度
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            switchNext(count: count + 1)
        }
    }
    switchNext(count: 0)
}

方案二:定时器触发

用Timer每隔固定时间触发一次Emoji切换,完成指定次数后停止定时器:

func pickingAnimation() {
    var switchCount = 0
    let totalSwitches = 10
    
    let timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { [weak self] timer in
        guard let self = self else {
            timer.invalidate()
            return
        }
        self.currentEmoji.text = self.randomEmoji().rawValue
        switchCount += 1
        if switchCount >= totalSwitches {
            timer.invalidate()
        }
    }
    timer.fire() // 立即执行第一次切换
}

注意事项

  • 所有UI操作必须在主线程执行,上面两种方案都满足这个要求
  • 不要使用Thread.sleep()这类阻塞主线程的方法,会导致APP无响应

内容的提问来源于stack exchange,提问作者Rayce Miller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 15:25:32