Last active
August 19, 2020 15:05
-
-
Save revblaze/76a9aae502fea1bcbf07c13147b54bfc to your computer and use it in GitHub Desktop.
Using Timer to determine ProgressBar value (NSProgressIndicator & UIActivityIndicator)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@IBOutlet var progressBar: NSProgressIndicator! // Progress Bar Object | |
var progressValue = 0.0 // Progress Bar Value (Double) | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
progressBar.doubleValue = progressValue | |
startProgressLoader() | |
} | |
func startProgressLoader() { | |
// The Timer closure will allow you to set a looping interval | |
Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in | |
self.progressValue += 2.0 // 0.1 * 2.0 = 20% bar progress per second | |
self.progressBar.doubleValue = self.progressValue | |
// Once progress reaches 100%, stop the Timer with invalidate() and | |
// set ProgressBar to indeterminate (or simply set .isHidden = true) | |
// Remember to .stopAnimation()! | |
if self.progressValue >= 100.0 { | |
timer.invalidate() | |
self.progressBar.isIndeterminate = true | |
self.endProgressLoader() | |
} | |
} | |
} | |
// BONUS: Fade out ProgressBar with animation | |
func endProgressLoader() { | |
NSAnimationContext.runAnimationGroup({ (context) -> Void in | |
content.duration = 1.0 // Set animation completion time to 1 second | |
progressBar.alpha = 0 // Fade out ProgressBar | |
}, completionHandler: { () -> Void in | |
self.progressBar.stopAnimation(self) // Stop background animation | |
)} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment