首页 > 解决方案 > 在 Swift 中使用按钮启动和停止动画

问题描述

我正在尝试使用 UIButton 来启动和停止已放入 imageview 的动画图像序列。我正在使用 swift 3.0

这是我当前的代码:

import UIKit

class ViewController: UIViewController {
    var selectedProgression : Int = 0

    var loading_1: UIImage!
    var loading_2: UIImage!
    var loading_3: UIImage!

    var animatedImage: UIImage!

    @IBOutlet weak var progressionAnimation: UIImageView!

    override func viewDidLoad() {

        loading_1 = UIImage(named: "blues-1")
        loading_2 = UIImage(named: "blues-2")
        loading_3 = UIImage(named: "blues-3")

        var images: [UIImage]!

        images = [loading_1, loading_2, loading_3]

        animatedImage = UIImage.animatedImage(with: images, duration: 3.0)

        progressionAnimation.image = animatedImage

        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

我已经看过并且对如何做到这一点有所了解,但是在将解决方案实际实施到我的代码中时一直卡住:(

根据我的发现,我需要为按钮创建一个出口来测量它是否被按下,并将按钮操作连接到按下时的 startAnimating 或 stopAnimating,具体取决于它的当前状态。

我在 Apple 文档https://developer.apple.com/documentation/uikit/uiimageview/1621061-startanimating上找到了 startAnimating 和 stopAnimating 函数,但不确定如何将它们实际实现到代码中。

任何帮助将不胜感激。谢谢!

标签: iosswiftanimationbuttontoggle

解决方案


如果要使用开始或停止动画,请不要使用 progreesionAnimation 的图像。

    progressionAnimation.animationImages =  images
    progressionAnimation.animationDuration = 1.0
    progressionAnimation.animationRepeatCount = 100
    progressionAnimation.startAnimating()

您应该使用您创建的图像数组中的动画图像。


推荐阅读