创建一个将通过一系列图像迭代的UIImageView



我想创建一个将通过一系列图像迭代的UIImageView。

我希望它能随着时间的推移而更快,不停止 - 直到用户按下按钮。

我刚刚在Swift和Xcode课程上完成了一个模块,我们创建了一个应用程序,该应用在您按"滚动"按钮时显示随机骰子面。

我想尝试以相反的方式进行,直到用户按下停止按钮,图像保持迭代速度更快。

我认为答案在下面 - 但是您如何使它变得更快,更快?

func animate_images()
{
    let myimgArr = ["1.jpg","2.jpg","3.jpg"]
    var images = [UIImage]()
    for i in 0..<myimgArr.count
    {
        images.append(UIImage(named: myimgArr[i])!)
    }
    imgView_ref.animationImages = images
    imgView_ref.animationDuration = 0.04
    imgView_ref.animationRepeatCount = 2
    imgView_ref.startAnimating()
}

然后将其添加到停止按钮:

imgView_ref.stopAnimating()

或有一种更简单的方法来解决此挑战?

也许您可以尝试使用计时器?计时器将允许您执行方法。在此方法中,您可以更新将更新ImageView.AnimationDuration值的TimeInterval值。

请参见下面的示例:

class YourViewController: UIViewController {
    @IBOutlet weak var imgView_ref: UIImageView!
    var timer: Timer?
    var timeInterval = 1.0
    override func viewDidLoad() {
        super.viewDidLoad()
        // Your code
        let myimgArr = ["1.jpg","2.jpg","3.jpg"]
        var images = [UIImage]()
        for i in 0..<myimgArr.count
        {
            images.append(UIImage(named: myimgArr[i])!)
        }
        imgView_ref.animationImages = images
        // You need to replace this line
        // imgView_ref.animationDuration = 0.04
        // with
        imgView_ref.animationDuration = timeInterval
        // Remove this line
        // imgView_ref.animationRepeatCount = 2
        imgView_ref.startAnimating()
        // Setup the timer
        timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: false)
    }
    // This method will be called by the timer each timeInterval
    @objc func updateTime() {
        // Just to be sure to have a positive timeInterval
        if timeInterval > 0.05 {
            // We remove 0.05 to the previous timeInterval
            timeInterval = timeInterval - 0.05
            // We update the imgView_ref
            imgView_ref.animationDuration = timeInterval
            imgView_ref.startAnimating()
            // We update the timer in order to call this method with the new timeInterval
            timer?.invalidate()
            timer = nil
            timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: false)
        }
    }
}

让我知道它是否适合您。

问候。