UIActivityIndicatorView not showing up when invoked from button action

前端 未结 1 1797
鱼传尺愫
鱼传尺愫 2021-01-24 00:37

I\'m trying to show a spinner during a possibly lengthy action invoked by a button press, but I can\'t get it to show up. Here\'s my code:

class ViewController:          


        
相关标签:
1条回答
  • 2021-01-24 01:04

    What you want is something like:

    @IBAction func buttonPressed(sender: UIBarButtonItem) {
      spinner.startAnimating()
      let dispatchPriority = DISPATCH_QUEUE_PRIORITY_DEFAULT
      dispatch_async(dispatch_get_global_queue(dispatchPriority, 0)) { 
    
        NSThread.sleepForTimeInterval(5.0) //your task here instead of this line
    
        dispatch_async(dispatch_get_main_queue(), {
          self.spinner.stopAnimating()
        })
      }
    }
    

    This starts the spinner,then dispatches to a background thread, performs a task there (I'm assuming the task you are performing is one that can be performed on a background thread - i.e it doesn't involve UI stuff). Once the task is complete, the method dispatches back to the main UI thread, and stops the spinner.

    0 讨论(0)
提交回复
热议问题