How do I make changes to my interface while a button is pressed

佐手、 提交于 2020-01-06 19:53:45

问题


I've got a button that will do some math when tapped. Depending on the equation that the user enters, the button will be tapped, but then stay down, as the app takes a while to do the math in the button's function. It would be great if I could have a progress bar show the user during that time. I added one, but the problem is that it doesn't show up when the button has been tapped, as the button is lagging.. it seems that no changes can occur on the screen while the button is tapped down and lagging.

Sorry... I'm a bit of a noob... but I'm stuck...


回答1:


You should do the math in a background thread, and all the UI related code in the main thread. For exemple, in Swift 3:

// Main thread by default: 
// show progress bar here.

DispatchQueue.global(qos: .background).async {
    // Background thread:
    // start your heavy process here, for example: 
    for index in 1...1000 {
        // do something in the loop

        DispatchQueue.main.async {
            // Main thread:
            // update your progress bar here
        }
    }

    DispatchQueue.main.async {
        // Main thread, called after the previous code:
        // hide your progress bar here
    }
}



回答2:


There is GCD. Here is a basic usage:

@IBAction func buttonPressed(sender: AnyObject)
{
   // show progress bar  
   dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
               //  start you main calculation 

        dispatch_async(dispatch_get_main_queue()) {
            // hide your progress bar
        }
    }
}

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




回答3:


I would add the progress bar on load but set it to invisible and then set it to visible as the first action of the button press method, Then do all of the math in the background.



来源:https://stackoverflow.com/questions/41528984/how-do-i-make-changes-to-my-interface-while-a-button-is-pressed

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