2016-11-03 5 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

실제로! 감사! –

관련 문제