从Timer选择器函数Swift调用函数的完成处理程序

时间:2019-06-24 11:30:43

标签: ios swift completionhandler

我具有animateButtons()功能,仅在动画结束时才需要设置完成处理程序。问题在于,在animateButtons()中,我只能在imageView.startAnimating()之后设置完成处理程序,因此整个定时都会受到影响,因为完成是用来启动其他动画的。我在另一篇帖子中读到了同样的确切问题,正如我实际上想做的那样,我应该设置一个NSTimer来设置完成处理程序,但是我真的不知道该怎么做。我已将NSTimer设置为调用setCompletion()函数,但如何设置它来调用animateButtons()完成处理程序?

您能指出我正确的方向吗?

这是函数和选择器函数:

static func animateButtons(completed: @escaping(Bool) ->(), imageView: UIImageView, images: [UIImage]) {
        imageView.animationImages = images
        imageView.animationDuration = 1.0 // check duration
        imageView.animationRepeatCount = 1
        imageView.startAnimating()

        _ = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(setCompletion), userInfo: nil, repeats: false)
        // completed(true)
}

@objc func setCompletion() {

}

2 个答案:

答案 0 :(得分:3)

您可以尝试使用内联回调

static func animateButtons(completed: @escaping(Bool) ->(), imageView: UIImageView, images: [UIImage]) {
    imageView.animationImages = images
    imageView.animationDuration = 1.0 // check duration
    imageView.animationRepeatCount = 1
    imageView.startAnimating() 
    Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false, block: { (t) in 
        t.invalidate()
        completed(true)
    })
}

顺便说一句,派遣后也可以做这项工作

static func animateButtons(completed: @escaping(Bool) ->(), imageView: UIImageView, images: [UIImage]) {
    imageView.animationImages = images
    imageView.animationDuration = 1.0 // check duration
    imageView.animationRepeatCount = 1
    imageView.startAnimating()
    DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
        completed(true)
    }
}

答案 1 :(得分:0)

方法1(我更喜欢这种方法)(如果要对Gif图像进行动画处理) 使用像Gifu https://github.com/kaishin/Gifu这样的第三方库来计算gif的运行时间。即使将来更改gif图像,它也将起作用。

    static func animateButtons(completed: @escaping(Bool) ->(), imageView: UIImageView, images: [UIImage]) {
imageView.prepareForAnimation(withGIFNamed: "welcome", loopCount: 1) {
            self.imageView.startAnimatingGIF()
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2 + self.imageView.gifLoopDuration, execute: {
                // Do your Task after animation completes
                )
        }
}

方法2(计算动画的运行时间并设置计时器)