求助:UIView.animate有限重复及自动反转在真机上出现跳变卡顿
按钮缩放动画真机跳变卡顿问题
我尝试给按钮实现一个从1.0到1.4的缩放动画,要求重复3次后停止,但在真机上出现跳变卡顿。模拟器运行流畅,但在iPhone 12 Pro(iOS 16)真机上,动画结束后会先跳至1.4的缩放比例,随后在completion回调设置transform = .identity时又跳回1.0。我怀疑过UIView.modifyAnimations的问题,但改用已废弃的UIView.setAnimationRepeatCount(3)后问题依旧。
问题代码
UIView.animate(withDuration: 0.5, delay: 0, animations: { UIView.modifyAnimations(withRepeatCount: 3, autoreverses: true) { self.titleButton.transform = CGAffineTransformMakeScale(1.4, 1.4) // self.titleButton.layoutIfNeeded() // doesn't change anything } }, completion: { _ in self.titleButton.transform = .identity })
解决办法
核心原因
开启autoreverses = true时,repeatCount = 3的动画执行流程是:1.0→1.4→1.0→1.4→1.0→1.4,最终视图会停在1.4的状态。而completion回调是在动画结束后同步执行,直接设置transform = .identity就会造成跳变。
最优解决方案
利用autoreverses和repeatCount的特性,让动画自动回到初始状态,不需要手动在completion里重置:
UIView.animate(withDuration: 0.5, delay: 0) { UIView.modifyAnimations(withRepeatCount: 3, autoreverses: true) { // 替换旧API为现代写法 self.titleButton.transform = CGAffineTransform(scaleX: 1.4, y: 1.4) } }
这样动画会完整执行3次「放大→还原」的循环,结束后自动停在1.0的初始状态,完全避免跳变。
备选方案(需保留completion逻辑时)
如果必须在completion里处理其他逻辑,可以把重置操作也包装成一个零时长动画,让UIKit平滑过渡:
UIView.animate(withDuration: 0.5, delay: 0, animations: { UIView.modifyAnimations(withRepeatCount: 3, autoreverses: true) { self.titleButton.transform = CGAffineTransform(scaleX: 1.4, y: 1.4) } }) { _ in UIView.animate(withDuration: 0.0) { self.titleButton.transform = .identity } }
内容的提问来源于stack exchange,提问作者thedp
相关产品推荐
相关产品推荐

