【问题标题】:How to animate a flashing UIView until a stop button is pressed?如何在按下停止按钮之前为闪烁的 UIView 设置动画?
【发布时间】:2017-07-24 22:58:13
【问题描述】:

我试图让 UIView 闪烁某种颜色,直到按下停止按钮。

我们将不胜感激。

【问题讨论】:

标签: ios objective-c animation uiview


【解决方案1】:

看看UIView的动画方法。具体看animateWithDuration:animations: 和变体之类的方法。带有选项的变体是您想要的。有重复和/或自动反转动画的选项。

编辑:

实际上,如果您希望颜色闪烁而不是颜色之间的交叉淡入淡出,那么使用UIView 动画可能不是最佳选择。这将导致颜色之间的平滑过渡。

如果您希望颜色从一种颜色闪烁到另一种颜色,最好使用计时器并简单地设置背景颜色。

我创建了一个简单的UIView 自定义子类,它有一个变量animateColor。将其设置为 true 并创建一个在背景颜色数组中循环的计时器。如果您希望它在颜色之间来回循环,请使用 2 种颜色。如果需要,可以使用更多。

public class LiveView: UIView {
  
  //Adjust this interval value if desired to get a different flash interval.
  //Note that changing the interval will have no effect while the timer is running.
  public var interval = 0.5
  
  //Change the array of colors if you want different colors
  public var backgroundColors = [UIColor.gray, UIColor.green, UIColor.blue, UIColor.red]
  var colorIndex = 0
  

  //Set this flag to true to animate between the colors. Set it to false to stop the animation.
  public var animateColor: Bool = false {
    didSet {
      if animateColor {
        colorTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true, block: {
          timer in
          self.colorIndex = (self.colorIndex + 1) % self.backgroundColors.count
          self.setColor()
        })
      } else {
        colorTimer?.invalidate()
      }
    }
  }
  private weak var colorTimer: Timer?

  func setColor() {
    backgroundColor = backgroundColors[colorIndex]
  }
  
  public required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setColor()
  }

  public override init(frame: CGRect) {
    super.init(frame: frame)
    setColor()
  }
}

【讨论】:

  • 好的,为什么要投反对票?我认为为含糊的“你能帮帮我”的问题提供代码是不合适的,但是将新开发人员指向正确的方向似乎会有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多