在Swift中使用按钮开始和停止动画

时间:2018-11-06 19:11:46

标签: ios swift animation button toggle

我正在尝试使用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函数,但不确定如何在代码中实际实现它们。

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

2 个答案:

答案 0 :(得分:0)

如何创建出口(here)。总结一下,打开助手编辑器(右上角的两个圆),然后在按住控件的同时将故事板中的按钮拖到Swift文件中。

您必须为此插座编写的IBAction看起来像这样:

@IBAction func starStopButtonPressed(_ sender: Any) {
    //Check if the progressionAnimation UIImageView is already animating
    if progressionAnimation.isAnimating { 
        progressionAnimation.stopAnimating() //If animating: stop animating
    else {
        progressionAnimation.startAnimating() //If not animating: start animating
    }
}

在创建新变量时,请注意!。如果您尝试在变量具有值之前使用它,则可能导致崩溃。

所以这个:

var images: [UIImage]!

images = [loading_1, loading_2, loading_3]

应该这样写:

var image: [UIImage] = [loading_1, loading_2, loading_3]

更少的线条使它看起来更干净,更安全。对loading_1-3 UIImage执行相同的操作,可以将其声明移至viewDidLoad函数内部。

就像这样:

var animatedImage: UIImage!

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

progressionAnimation.image = animatedImage

如果这样写,它将既干净又安全:

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

答案 1 :(得分:0)

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

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

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

相关问题