Остановите старую анимацию и начните новую, как только я изменю сегменты, быстро - PullRequest
0 голосов
/ 08 февраля 2019

Есть ли метод или функция, которая может остановить предыдущую анимацию, когда я переключаю элементы управления сегментами?Если я не удаляю анимацию, изображение, которое исчезало в первом сегменте, начинает вращаться во втором, а затем перемещается в третий сегмент.Несмотря на то, что я переключаю сегменты, он все время работает как добавление различных анимаций.

Я пытался: - удалитьAllAnimations (), но он не работает должным образом.- self.view.layer.removeAnimation (forKey: "moveAnimation").Пробовал это один в конце кода для каждого выбора сегмента.

Возможно, я не помещаю это в правильное место, но я не могу заставить его работать должным образом

Вот мой код:

import UIKit

class MoveViewController: UIViewController {


    @IBOutlet var sgAction : UISegmentedControl!

    var moveLayer : CALayer?

    @IBAction func segmentDidChange(sender : UISegmentedControl){
        updateAction()

    }


    func updateAction(){
        let action = sgAction.selectedSegmentIndex

        if action == 0 {
            //fade

            let fadeAnimation = CABasicAnimation(keyPath: "opacity")

            self.view.layer.removeAnimation(forKey: "fadeAnimation")

            fadeAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
            fadeAnimation.fromValue = NSNumber.init(value: 1.0)
            fadeAnimation.toValue = NSNumber.init(value: 0.0)
            fadeAnimation.isRemovedOnCompletion = false

            fadeAnimation.duration = 3.0
            fadeAnimation.beginTime = 1.0
            fadeAnimation.isAdditive = false
            fadeAnimation.fillMode = CAMediaTimingFillMode.both
            fadeAnimation.repeatCount = Float.infinity
            moveLayer?.add(fadeAnimation, forKey: nil)

        } else if action == 1 {
            //2. rotate

            let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")

            self.view.layer.removeAnimation(forKey: "rotateAnimation")

            rotateAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
            rotateAnimation.fromValue = 0
            rotateAnimation.toValue = 2 * Double.pi

            rotateAnimation.isRemovedOnCompletion = false

            rotateAnimation.duration = 1.0
            rotateAnimation.repeatCount = Float.infinity
            moveLayer?.add(rotateAnimation, forKey:nil)


        } else {
            //3. move

            let moveAnimation = CABasicAnimation(keyPath: "position")
            self.view.layer.removeAnimation(forKey: "moveAnimation")

            moveAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)

            moveAnimation.fromValue = NSValue.init(cgPoint: CGPoint(x: 0, y: 0))
            moveAnimation.toValue = NSValue.init(cgPoint: CGPoint(x: 700, y: 500))
            moveAnimation.isRemovedOnCompletion = false
            moveAnimation.duration = 3.0
            moveAnimation.repeatCount = Float.infinity
            moveLayer?.add(moveAnimation, forKey: nil)

        }
    }
//        moveLayer?.removeAllAnimations()




    func createImg(){
        let displayImage = UIImage(named: "balloon.png")
        moveLayer = CALayer.init()
        moveLayer?.contents = displayImage?.cgImage
        moveLayer?.bounds = CGRect(x: 0, y: 0, width: 150, height: 150)
        moveLayer?.position = CGPoint(x: 300, y: 200)
        self.view.layer.addSublayer(moveLayer!)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        createImg()
//      moveLayer?.removeAllAnimations()
        updateAction()

    }

}

1 Ответ

0 голосов
/ 09 февраля 2019

Когда вы добавляете moveLayer?.removeAllAnimations() и self.moveLayer.layoutIfNeed() к segmentDidChange(sender : UISegmentedControl).Также другим ключевым элементом, который необходимо изменить, является moveLayer?.add(fadeAnimation, forKey: "nil") на moveLayer?.add(fadeAnimation, forKey: "fadeAnimation").

import UIKit

class MoveViewController: UIViewController {

    @IBOutlet var sgAction : UISegmentedControl!

    var moveLayer : CALayer?

    override func viewDidLoad() {
        super.viewDidLoad()
        createImg()
        updateAction()
    }

    @IBAction func segmentDidChange(sender : UISegmentedControl){
        moveLayer?.removeAllAnimations()
        self.moveLayer?.layoutIfNeeded()
        updateAction()
    }

    func updateAction(){
        switch sgAction.selectedSegmentIndex {
        case 0:
            //fade
            let fadeAnimation = CABasicAnimation(keyPath: "opacity")

            fadeAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
            fadeAnimation.fromValue = NSNumber.init(value: 1.0)
            fadeAnimation.toValue = NSNumber.init(value: 0.0)
            fadeAnimation.isRemovedOnCompletion = false

            fadeAnimation.duration = 3.0
            fadeAnimation.beginTime = 1.0
            fadeAnimation.isAdditive = false
            fadeAnimation.fillMode = CAMediaTimingFillMode.both
            fadeAnimation.repeatCount = Float.infinity
            moveLayer?.add(fadeAnimation, forKey: "fadeAnimation")

        case 1:
            //2. rotate
            let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")

            rotateAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
            rotateAnimation.fromValue = 0
            rotateAnimation.toValue = 2 * Double.pi

            rotateAnimation.isRemovedOnCompletion = false

            rotateAnimation.duration = 1.0
            rotateAnimation.repeatCount = Float.infinity
            moveLayer?.add(rotateAnimation, forKey: "rotateAnimation")

        case 2:
            //3. move
            let moveAnimation = CABasicAnimation(keyPath: "position")

            moveAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)

            moveAnimation.fromValue = NSValue.init(cgPoint: CGPoint(x: 0, y: 0))
            moveAnimation.toValue = NSValue.init(cgPoint: CGPoint(x: 700, y: 500))
            moveAnimation.isRemovedOnCompletion = false
            moveAnimation.duration = 3.0
            moveAnimation.repeatCount = Float.infinity
            moveLayer?.add(moveAnimation, forKey: "position")
        default: break

        }
    }

    func createImg(){
        let displayImage = UIImage(named: "balloon.png")
        moveLayer = CALayer.init()
        moveLayer?.contents = displayImage?.cgImage
        moveLayer?.bounds = CGRect(x: 0, y: 0, width: 150, height: 150)
        moveLayer?.position = CGPoint(x: 300, y: 200)
        self.view.layer.addSublayer(moveLayer!)
    }

}
...