swift - 如何在ios程序开发中正确使用activity indicator(菊花等待图标)?
高洛峰
高洛峰 2017-04-18 09:42:22
0
2
693

我想达到的效果是这样的:
点击按钮

图片ImageView处的占位图消失

图片处开始显示菊花动画图标

旋转五秒中

菊花图标停止并消失

显示新的图片

部分代码如下:

class ViewController: UIViewController {
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
    @IBAction func clickButton(_ sender: UIButton) {
        imageView.image = nil
        activityIndicator.startAnimating()
        sleep(5)
        activityIndicator.stopAnimating()
        imageView.image = UIImage(named: "cat")
    }
}

页面设计

实际效果是点击按钮之后,什么都没有发生,五秒钟之后换成了新的图片。
请问正确的写法应该是怎样的?

我的全部源码在这里:https://github.com/Stanley-Ti...
编程环境是Xcode8 Swift3

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
Ty80

I’ll give you two ideas. They may not be the best, but I hope they are useful to you. First of all, sleep(5) is written in the main thread, so the chrysanthemum has actually started to animate, but when sleep(5) is executed, the main thread sleeps, and the runloop does not receive touch events and does not update the UI interface, so You can't see the animation effect of the chrysanthemum. When the main thread is awakened after 5 seconds, stopAnimating is directly executed, and then the new picture is displayed. You can use the afterAPI provided by GCD:

imageView.image = nil
activityIndicator.startAnimating()
let delay = DispatchTime.now() + DispatchTimeInterval.seconds(5)
DispatchQueue.main.asyncAfter(deadline: delay) {
        activityIndicator.stopAnimating()
        imageView.image = UIImage(named: "cat")
}

If you still want to continue using sleep, you can open a sub-thread, but it is more troublesome:

DispatchQueue.global().async {
    DispatchQueue.main.async {
        imageView.image = nil
        activityIndicator.startAnimating()
    }
    sleep(5)
    DispatchQueue.main.async {
        activityIndicator.stopAnimating()
        imageView.image = UIImage(named: "cat")
    }
}
巴扎黑

Intuition, there is something wrong with sleep(5).
sleep will cause the CPU to stop processing operations. In this way, when it is enabled, the UI cannot be updated and nothing happens.

Use dispatch_after() to replace sleep() to handle delays.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!