如何通过UIViewPropertyAnimator实现重复反转的屏幕渐变动画?
没问题!你完全可以实现这种平滑的黑↔白循环动画,不需要手动写反向动画的代码,两种简单方案送给你:
方案一:用UIView基础动画(简单快捷)
这种方式代码量最少,适合快速实现需求,通过autoreverse和repeatCount就能自动完成反向和循环:
override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let animationDuration: TimeInterval = 4 // 单次黑→白的时长 let repeatCount: Float = 3 // 你想要的完整循环次数(黑→白→黑算一次完整循环) UIView.animate(withDuration: animationDuration, delay: 0, options: [.autoreverse, .repeat], animations: { self.view.backgroundColor = .white }, completion: nil) }
.autoreverse:让动画执行完成后自动反向运行(从白平滑切回黑).repeat:让整个动画(正向+反向)重复执行,配合repeatCount可以指定有限次数(如果不设置repeatCount,默认是无限循环)
如果需要在动画全部结束后执行额外逻辑,可以改成这样:
override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let animationDuration: TimeInterval = 4 let totalCycles = 3 // 完整循环次数 let totalAnimationDuration = animationDuration * 2 * Double(totalCycles) UIView.animate(withDuration: animationDuration, delay: 0, options: [.autoreverse, .repeat], animations: { self.view.backgroundColor = .white }, completion: nil) // 延迟到所有动画结束后执行操作 DispatchQueue.main.asyncAfter(deadline: .now() + totalAnimationDuration) { print("所有循环动画已结束") } }
方案二:用UIViewPropertyAnimator实现(适配你的原有代码)
如果你更倾向于用UIViewPropertyAnimator(比如需要更灵活的动画控制,比如中途暂停、调整速度),可以通过设置它的autoreverses和repeatCount属性来实现:
override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let animationDuration: TimeInterval = 4 let repeatCount: Float = 3 // 指定重复次数 // 创建动画器,定义正向动画(黑→白) let animator = UIViewPropertyAnimator(duration: animationDuration, curve: .linear) { self.view.backgroundColor = .white } // 开启自动反转和指定重复次数 animator.autoreverses = true animator.repeatCount = repeatCount // 启动动画 animator.startAnimation() // 可选:添加动画完成后的回调 animator.addCompletion { position in if position == .end { print("所有循环动画执行完毕") } } }
这种方式和你原来的代码结构更契合,而且UIViewPropertyAnimator提供了更多高级控制能力,比如可以随时暂停、继续动画,或者调整动画的进度。
内容的提问来源于stack exchange,提问作者Ben Cavenagh
相关产品推荐
相关产品推荐

