【发布时间】:2017-07-24 22:58:13
【问题描述】:
我试图让 UIView 闪烁某种颜色,直到按下停止按钮。
我们将不胜感激。
【问题讨论】:
-
你能再解释一下,并展示一些你尝试过的代码吗?
标签: ios objective-c animation uiview
我试图让 UIView 闪烁某种颜色,直到按下停止按钮。
我们将不胜感激。
【问题讨论】:
标签: ios objective-c animation uiview
看看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()
}
}
【讨论】: