如何临时暂停函数执行以实现逐帧切换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
相关产品推荐
相关产品推荐

