使用线程通过Swift更新UI [英] Using threads to update UI with Swift

查看:403
本文介绍了使用线程通过Swift更新UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swift使用Xcode 6开发软件.当我按下一个按钮时,我的代码从网络上获取了一些信息,并将其写在我的NSWindow上.

I'm developing a software with Xcode 6 using Swift. When I press a button, my code takes some informations from the web and writes them on my NSWindow.

所以想像这样:

@IBAction func buttonPressed(sender: AnyObject)
{
    for page in listOfPages                     //Number of pages is 40.
    {
        var label: NSTextField = NSTextField();

        label.stringValue = getInformetionsFromPage(page)

        /*
             some code to add label in the window here 
        */ 
    }
}

问题在于,一旦我单击该按钮,通常需要一会儿时间才能看到结果列表,这主要是因为该应用程序被冻结了.那是因为我没有使用任何线程来处理此问题.我如何实现线程以查看循环的每个步骤中更新的每个标签?我是线程和Swift的新手,所以我需要一些帮助!

The problem is that once I click the button, it takes a while before I see the list of results, in the main time the app is frozen. That's because I'm not using any threads to handle this problem. How could I implement threads to see every label updated every step of the loop? I'm new with threads and Swift, so I would need some help!

谢谢你们.

推荐答案

GCD .这是基本用法:

for page in listOfPages {
    var label = NSTextField()
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
        let result = getInformationFromPage(page)
        dispatch_async(dispatch_get_main_queue()) {
            label.stringValue = result
        }
    }
}

dispatch_async函数在给定队列上异步运行代码块.在第一个dispatch_async调用中,我们调度代码在后台队列上运行.得到result后,我们用该result

dispatch_async function asynchronously runs the block of code on the given queue. In first dispatch_async call we dispatch the code to run on background queue. After we get result we update label on main queue with that result

这篇关于使用线程通过Swift更新UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆