search

Home  >  Q&A  >  body text

swift - 如何在ios程序开发中正确使用activity indicator(菊花等待图标)?

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

图片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

高洛峰高洛峰2767 days ago757

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 09:44:22

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

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 09:44:22

    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.

    reply
    0
  • Cancelreply