Home > database >  Start an indeterminate progress bar when a button is clicked
Start an indeterminate progress bar when a button is clicked

Time:10-12

I'm writing an application in Swift. I've been searching for how to start an indeterminate progress bar when an action is being done, but there doesn't seem to be any results. I want the indeterminate progress bar to run when an action is running instead the system says "Applications not responding", here is my progress bar function:

@IBOutlet weak var progressBar: NSProgressIndicator!

CodePudding user response:

This is a simple playground test (make sure you create use Blank from the macOS templates)

import AppKit
import PlaygroundSupport

let view = NSView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))

let progressBar = NSProgressIndicator(frame: CGRect(x: view.bounds.midX - 60, y: 0, width: 120, height: 32))

view.addSubview(progressBar)
progressBar.isIndeterminate = true
progressBar.style = .bar

// Present the view in Playground
PlaygroundPage.current.liveView = view

progressBar.startAnimation(nil)

DispatchQueue.global().async {
    Thread.sleep(forTimeInterval: 5)
    DispatchQueue.main.async {
        progressBar.stopAnimation(nil)
    }
}

This will present a indeterminate playground and after 5 seconds it will stop animating.

The point here is, you are likely blocking the "main" thread, which is why you're getting "Applications not responding", but you also need to ensure that any updates made to the UI are done only on the "main" thread.

The use of DispatchQueue.global().async and Thread.sleep(forTimeInterval: 5) is for demonstration purposes only, instead, what ever long running/blocking work your doing would be executed within the DispatchQueue.global() context

  • Related