如何在Swift 3.0中使用动画创建时间延迟

时间:2017-12-02 20:15:00

标签: ios swift animation imageview

  1. 首先我们生成一个随机数(例如从0到10):

    If randomNumber = 0
        Animate imageSet0 [here we create an ImageArray and an animate function – please see code below)
    Else if randomNumber = 1
        Animate imageSet1
    Else if randomNumber = 2
        Animate imageSet2
    And so on…
    
  2. 然后我们放置一个等待上述动画完成的DispatchQueue计时器(时间延迟等于animationDuration),然后我们重复上面的第一步并生成另一个随机数,播放另一个动画集:

    DispatchQueue.main.asyncAfter(deadline: .now() + imageView.animationDuration) {
       [Insert code that repeats the first step above and generates another random number to play another animation set]
    }
    
  3. 理论上,这个随机动画可以无限期播放,直到用户移过这个场景。

  4. 到目前为止,这是我的代码:

    func createImageArray(total: Int, imagePrefix: String) -> [UIImage]{
        var imageArray: [UIImage] = []
        for imageCount in 0..<total {
            let imageName = "\(imagePrefix)-\(imageCount).png"
            let image = UIImage(named: imageName)!
    
            imageArray.append(image)
        }
    
        return imageArray
    
    }
    
    
    func animate(imageView: UIImageView, images: [UIImage]){
        imageView.animationImages = images
        imageView.animationDuration = 1.0
        imageView.animationRepeatCount = 1
        imageView.startAnimating()
    
        DispatchQueue.main.asyncAfter(deadline: .now() + imageView.animationDuration) {
    
    [Create code that repeats the first step above and generates another random number to play another animation set]
    
        }
    }
    

1 个答案:

答案 0 :(得分:0)

您可以使用UIView.animate(withDuration: delay: options: animations:) api。注意延迟参数将允许您在一定延迟后开始动画。