2016-11-03 4 views
0

私はこのシナリオをUIViewのアニメーションで問題なく使用しましたが、CALayerアニメーションでは使用できません。進行中のCALayerアニメーションの再起動方法は?

私は、問題を実証するための遊び場を作っています

import UIKit 
import PlaygroundSupport 

class EventHandler { 
    @objc func onClick(_ button: UIButton) { 

     button.layer.removeAllAnimations() 

     button.layer.borderColor = UIColor.red.cgColor 
     print("RED") 

     CATransaction.begin() 
     CATransaction.setCompletionBlock({ 
      button.layer.borderColor = UIColor.black.cgColor 
      print("BLACK") 
     }) 

     let colorAnimation = CABasicAnimation() 
     colorAnimation.toValue = UIColor.black.cgColor 
     colorAnimation.duration = 5 
     button.layer.add(colorAnimation, forKey: "borderColor") 
     CATransaction.commit() 

    } 
} 

let eventHandler = EventHandler() 

let button = UIButton(frame: CGRect.init(x: 0, y: 0, width: 200, height: 200)) 

button.backgroundColor = UIColor.gray 
button.layer.borderColor = UIColor.black.cgColor 
button.layer.borderWidth = 20 
button.addTarget(eventHandler, action: #selector(EventHandler.onClick(_:)), for: .touchDown) 

PlaygroundPage.current.liveView = button 

私が欲しい私は、アニメーションの途中でボタンをクリックすると、アニメーションを最初からやり直す必要があります。しかし、removeAllAnimations()を呼び出すと、元のアニメーションの完了ブロックが実行されてから、色を赤に設定する前ではなく実行したように見えます。

+0

は、私は、ボタンがアニメーションでないとき、それは黒だと、赤から黒への境界線の色をアニメーション化することを意図していることを正しく理解し、アニメーションを再起動したときには再起動であることが再び赤にジャンプすることがありますか? –

+0

はい、それは私が望んだことです。私は、fromValueをアニメーションオブジェクトに設定することによって解決策を見つけました。 –

答えて

1

fromValueをアニメーションオブジェクトに設定することで問題を解決しました。ここでは作業バージョンです:

import UIKit 
import PlaygroundSupport 

class EventHandler { 
    @objc func onClick(_ button: UIButton) { 

     button.layer.removeAllAnimations() 

     let colorAnimation = CABasicAnimation() 
     colorAnimation.fromValue = UIColor.red.cgColor 
     colorAnimation.toValue = UIColor.black.cgColor 
     colorAnimation.duration = 5 
     button.layer.add(colorAnimation, forKey: "borderColor") 
    } 
} 

let eventHandler = EventHandler() 

let button = UIButton(frame: CGRect.init(x: 0, y: 0, width: 200, height: 200)) 

button.backgroundColor = UIColor.gray 
button.layer.borderColor = UIColor.black.cgColor 
button.layer.borderWidth = 20 
button.addTarget(eventHandler, action: #selector(EventHandler.onClick(_:)), for: .touchDown) 

PlaygroundPage.current.liveView = button 
+1

この場合、完了ブロックは必要ありません(プロパティ値は常に黒色です)。 –

+0

本当に!ありがとう! –

関連する問題