1

我想在应用程序向用户显示其视图之前加载一组图像,自定义延迟例如 5 毫秒。有什么帮助吗??

我在 UIViewController 中使用了 UIImageView,这是我的代码:

import UIKit

class CustomViewController: UIViewController {


@IBOutlet weak var imageView: UIImageView!

var logoImage: [UIImage] = [
    UIImage(named: "splash_logo_1.png")!,
    UIImage(named: "splash_logo_2.png")!,
    UIImage(named: "splash_logo_3.png")!,
    UIImage(named: "splash_logo_4.png")!,
    UIImage(named: "splash_logo_5.png")!,
    UIImage(named: "splash_logo_6.png")!,
    UIImage(named: "splash_logo_7.png")!,
    UIImage(named: "splash_logo_8.png")!,
    UIImage(named: "splash_logo_9.png")!,

]

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.8 , execute: {
        // Put your code which should be executed with a delay here
        for i in 1..<self.logoImage.count
        {
            let image = self.logoImage[i]
            self.imageView.image = image
        }
    })

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

构建应用程序后,它只显示最后一张图片 (plash_logo_9.png)。

那么问题出在哪里..?

4

2 回答 2

2

//试试这个,

override func viewDidLoad() {
    super.viewDidLoad()

    imageView.tag = 0
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.8 , execute: {
        self.changeImage()
    })
}

func changeImage() {
    let image = self.logoImage[imageView.tag]
    self.imageView.image = image

    imageView.tag += 1
    if imageView.tag == logoImage.count {
        //stop the animation
        //Show its views to user
        return
    }

    DispatchQueue.main.asyncAfter(deadline: .now() + 0.8 , execute:
    {
        self.changeImage()
    })
}
于 2017-01-06T10:36:28.333 回答
1

您开始为用户显示图像太快了。viewDidLoad仅表示您的 viewController 已加载到内存中,并准备好进行初始设置,但是,用户看不到它。

为了使演示文稿对用户可见,我建议开始在 中显示它viewDidAppear,并且只将第一张图像设置在viewDidLoad.

最后,您应该更改fordispatch调用顺序。您需要创建尽可能多的调度块,延迟不断增加,就像您拥有的图像一样多。

因此,将其删除viewDidLoad并替换为:

 override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        var delay: Double = 0 
        for i in 0..<self.logoImage.count {
            DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {
                // Put your code which should be executed with a delay here
                let image = self.logoImage[i]
                self.imageView.image = image
            })
            delay += 0.8
        }
    }

此外,我建议阅读有关viewControllers 生命周期的更多信息。

于 2017-01-06T09:42:24.227 回答