Search code examples
iosswiftiphoneactivity-indicator

How to use one activity indicator in several views in Swift?


I am new in Swift, so please keep that in mind.
I am building an app that sends a lot of API calls that takes pretty long time, and I am using just normal activity indicator to let users know the app is working and is fine.

It is tedious to create a new activity indicator every time I create a new view, so is there any way to avoid creating activity indicator every time?
Is there any way to use just one activity indicator that can be used throughout the views?

Thank you in advance.


Solution

  • It's totally fine to create new views like this one on each screen, it does not load the system, so you don't need to reuse them

    If you have duplicate code of setting your view up, you can move it into such extension:

    extension UIActivityIndicatorView {
        static func createGeneral() -> UIActivityIndicatorView {
            let activityIndicatorView = UIActivityIndicatorView(style: .large)
            
            // if you're using it with constraints
            activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
            
            activityIndicatorView.color = .black
            // and other setup you need
            
            return activityIndicatorView
        }
    }
    

    Usage:

    let activityIndicatorView = UIActivityIndicatorView.createGeneralIndicator()