【问题标题】:iOS blink animation on UIView with finite number of timesiOS 在 UIView 上闪烁动画,次数有限
【发布时间】:2018-11-06 12:03:06
【问题描述】:

我正在尝试在 UIView 上创建闪烁效果。目前,我正在使用使 UIView 闪烁无数次的代码。代码看起来像这样

到目前为止我做了什么:

 func startBlink() {
                  UIView.animate(withDuration: 0.8,//Time duration
                                delay:0.0,
                                options:[.allowUserInteraction, .curveEaseInOut, .autoreverse, .repeat],
                                animations: { self.alpha = 0 },
                                completion: nil)
        }

但是这段代码使 ui 视图闪烁了无数次。我使用了另一个代码,但它只闪烁了一次。

我想要什么:

所以我非常接近,但我真的想闪烁 UIView 有限 次数,即 30 次,并且必须在第 30 次闪烁后停止。

请帮助我,我想我的问题很清楚。请帮帮我。

【问题讨论】:

  • 考虑使用定时器。计算它触发的次数,然后使计时器无效。
  • 你在UIView的扩展里面实现了这个功能吗?

标签: ios uiview swift4 xcode9.4


【解决方案1】:

使用此功能为视图设置动画。希望对你有帮助

extension UIView {  
        func flash(numberOfFlashes: Float) {
           let flash = CABasicAnimation(keyPath: "opacity")
           flash.duration = 0.2
           flash.fromValue = 1
           flash.toValue = 0.1
           flash.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
           flash.autoreverses = true
           flash.repeatCount = numberOfFlashes
           layer.add(flash, forKey: nil)
       }
 }

【讨论】:

  • 假设我想在 numberOfFlashes 完成之前移除 flash。那会是layer.removeAllAnimations() 吗?还是layer.removeAnimation(forKey:"opacity")
  • 两个都试了,只有第一个有效。我注意到没有 forKeyPath: 选项,就像动画的设置方式和使用 forKey: 在我的评论中一样,不起作用。
  • 有一个forKeyPath: 选项不起作用,因为带有该键的动画不在列表中。您可以从 layer.animationKeys() 检查活动动画
  • 我的意思是编译器声明forKeyPath: 没有签名。下次有机会我会再试一次。也许这是重新启动 Xcode 修复的那些事情之一。 :)
  • 我在此处的文档中看不到删除带有keyPath 的动画的选项。 developer.apple.com/documentation/quartzcore/calayer
【解决方案2】:

有一个内置的类函数用于计数并在块中调用它。

class func setAnimationRepeatCount(_ repeatCount: Float)

  func startBlink() {
              UIView.animate(withDuration: 0.8,//Time duration
                            delay:0.0,
                            options:[.allowUserInteraction, .curveEaseInOut,    .autoreverse, .repeat],
                            animations: { 

       UIView.setAnimationRepeatCount(30) // repeat 30 times.

     self.alpha = 0 
       },
                            completion: nil)
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    相关资源
    最近更新 更多