2016-11-03 3 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(), блок завершения исходной анимации выполняется до того, как я установил цвет в RED, но после него.

+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

Действительно! Благодаря! –