我是UI编程的新手,现在我正试图根据屏幕点击的次数来制作屏幕脉冲。我的问题是,当检测到点击并缩短动画的持续时间时,它会从头开始动画,在重新启动时创建白色闪光。如何在检测到水龙头的任何时刻开始加速动画。
我的代码:
class ViewController: UIViewController {
var tapCount: Int = 0
var pulseSpeed: Double = 3
override func viewDidLoad() {
super.viewDidLoad()
counter.center = CGPoint(x: 185, y: 118)
pulseAnimation(pulseSpeed: pulseSpeed)
}
func pulseAnimation(pulseSpeed: Double) {
UIView.animate(withDuration: pulseSpeed, delay: 0, options: [UIViewAnimationOptions.repeat, UIViewAnimationOptions.autoreverse],
animations: {
self.red.alpha = 0.5
self.red.alpha = 1.0
})
}
@IBOutlet weak var red: UIImageView!
@IBOutlet weak var counter: UILabel!
@IBAction func screenTapButton(_ sender: UIButton) {
tapCount += 1
counter.text = "\(tapCount)"
pulseSpeed = Double(3) / Double(tapCount)
pulseAnimation(pulseSpeed: pulseSpeed)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
答案 0 :(得分:0)
您需要直接使用Core Animation来实现您所追求的目标,而不是依赖于内置于顶层的UIView
动画。
// create animation in viewDidLoad
let pulseAnimation = CABasicAnimation(keyPath: "opacity")
pulseAnimation.fromValue = 0.5
pulseAnimation.toValue = 1.0
pulseAnimation.autoreverses = true
pulseAnimation.duration = 3.0
pulseAnimation.repeatCount = .greatestFiniteMagnitude
// save animation to property on ViewController
self.pulseAnimation = pulseAnimation
// update animation speed in screenTapButton
pulseAnimation.speed += 0.5
您可能想稍微使用速度数字。默认速度为1.0,动画指定持续时间为3秒,因此从0.5到1.0需要6秒才能恢复到0.5。在2.0的速度下,相同的动画将快速发生两次,或者整个周期发生3秒。
我希望有所帮助!