【问题标题】:Calling completion handler of a function from Timer selector function Swift从 Timer 选择器函数 Swift 调用函数的完成处理程序
【发布时间】:2019-06-24 11:30:43
【问题描述】:

我有 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() {

}

【问题讨论】:

    标签: ios swift completionhandler


    【解决方案1】:

    你可以尝试使用内联回调

    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)
        }
    }
    

    【讨论】:

    • 哇!太好了,再次感谢。我刚试过你的Timer,效果很好。我也会尝试GDC 解决方案,以便了解更多信息。再次感谢您。
    【解决方案2】:

    方法 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
                    )
            }
    }
    

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

    【讨论】:

    • 谢谢!我绝对会试一试的。看起来很有用。
    猜你喜欢
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    相关资源
    最近更新 更多