按下按钮时如何更改我的界面 [英] How do I make changes to my interface while a button is pressed

查看:31
本文介绍了按下按钮时如何更改我的界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮,可以在点击时进行一些数学运算.根据用户输入的等式,按钮将被点击,但随后保持按下状态,因为应用程序需要一段时间来计算按钮的功能.如果我能在这段时间内向用户显示进度条,那就太好了.我添加了一个,但问题是当按钮被点击时它不显示,因为按钮滞后..当按钮被点击并滞后时,屏幕上似乎不会发生任何变化.

对不起...我有点菜鸟...但我被卡住了...

解决方案

您应该在后台线程中进行数学运算,而所有与 UI 相关的代码都应在主线程中进行.例如,在 Swift 3 中:

//默认主线程://在此处显示进度条.DispatchQueue.global(qos: .background).async {//后台线程://在这里开始你的繁重过程,例如:对于 1...1000 中的索引 {//在循环中做一些事情DispatchQueue.main.async {//主线程://在这里更新你的进度条}}DispatchQueue.main.async {//主线程,在前面的代码之后调用://在这里隐藏你的进度条}}

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

解决方案

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

这篇关于按下按钮时如何更改我的界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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