2017-04-30 42 views
0

我是新用戶界面編程,現在我試圖根據屏幕被點擊的次數以一定的速度製作屏幕脈衝。我的問題是,當檢測到輕擊並且縮短動畫的持續時間時,它會從頭開始動畫,並在重新開始時創建白色閃光。我將如何從檢測到輕敲時的任何點開始加速動畫。如何在使用swift的情況下加速動畫?

我的代碼:

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

您需要使用的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回到0.5需要6秒。在2.0的速度下,相同的動畫將發生兩次,或整個週期3秒。

我希望有幫助!

相關問題