如何在按下button的同时对界面进行更改

我有一个button,将点击时会做一些math。 根据用户input的公式,该button将被轻敲,但随后停留下来,因为应用程序需要一段时间来执行buttonfunction中的math运算。 如果我能在这段时间有一个进度条显示用户,那将是非常棒的。 我添加了一个,但问题是,它不会显示,当button已被轻拍,因为button是滞后的。看起来没有变化可以发生在屏幕上,而button被击倒和滞后。

对不起…我有一点小菜…但是我被卡住了…

您应该在后台线程中执行math运算,并在主线程中执行所有与UI相关的代码。 例如,在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 } } 

有GCD 。 这是一个基本用法:

 @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函数asynchronous运行给定队列上的代码块。 在第一个dispatch_async调用中,我们调度要在后台队列上运行的代码。 得到结果后,我们用主结果更新主队列上的标签

我将在加载时添加进度条,但将其设置为不可见,然后将其设置为可见,作为button按下方法的第一个操作,然后在后台执行所有的math操作。