Using threads to update UI with Swift

不羁岁月 提交于 2020-01-01 01:53:10

问题


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.

So imagine something like this:

@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 
        */ 
    }
}

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!

Thank you guys.


回答1:


There is GCD. Here is a basic usage:

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




回答2:


Swift 3.0 + version

DispatchQueue.main.async() {
    // your UI update code
}

Posted this because XCode cannot suggest the correct syntax from swift 2.0 version



来源:https://stackoverflow.com/questions/27212254/using-threads-to-update-ui-with-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!