UIActivityIndi​​cator没有旋转GCD

时间:2016-05-12 02:28:57

标签: ios swift grand-central-dispatch

我正在制作一个非常简单的应用程序来使用GCD练习多线程。我在我的ViewController类中初始化了一个UIActivityIndi​​catorView,如下所示:

class ViewController: UIViewController {

var myActivityIndicator:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)

在我的viewDidLoad中,我使用以下代码将其作为子视图添加到主视图中:

 override func viewDidLoad()
{
    super.viewDidLoad()

    myActivityIndicator.center = view.center
    view.addSubview(myActivityIndicator)
}

然后当点击我的按钮时,我有一个IBAction,通过在一段时间后打印一条简单的消息来处理事件。这是代码:

@IBAction func doSomething(sender: AnyObject)
{
    let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
    dispatch_async(dispatch_get_global_queue(priority, 0))
    {
        self.myActivityIndicator.startAnimating()

        sleep(3)

        print("This has been accessed on another thread")

        dispatch_async(dispatch_get_main_queue())
        {
            self.myActivityIndicator.stopAnimating()
        }
    }
}

似乎没有调用self.myActivityIndi​​cator.startAnimating(),但是当我将这行代码放在viewDidLoad中时,它的工作正常。

我错过了什么?

2 个答案:

答案 0 :(得分:0)

这是通过在主线程上启动动画来解决的:

 @IBAction func doSomething(sender: AnyObject)
{
    self.myActivityIndicator.startAnimating()
...

答案 1 :(得分:0)

只有主线程可以更新UI。因此,您必须将更新UI的操作放在主线程中。添加 dispatch_async(dispatch_get_main_queue()){updateSomeUI(); }

但是当在viewDidLoad()中加载视图控制器时,它恰好发生在主线程中,它可以立即更新UI。 When code executed in viewDidLoad() When code executed in buttonClick()

@IBAction func doSomething(sender: AnyObject)
{
    let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
    dispatch_async(dispatch_get_global_queue(priority, 0))
    {
        dispatch_async(dispatch_get_main_queue()) 
        {
            self.myActivityIndicator.startAnimating()
        }

        sleep(3)

        print("This has been accessed on another thread")

        dispatch_async(dispatch_get_main_queue())
        {
            self.myActivityIndicator.stopAnimating()
        }
    }
}

- 好运。