How Create UIActivityIndicator computed property from a function in extension

82 Views Asked by At

I have managed to create a UIActivityIndicatorView extension for turning animating it to start and stop. However I would like make it better by using a computed property of type bool using a get and set. I have tried but can't think of way to do it. How could I refactor this.

extension UIActivityIndicatorView {
    func loadingIndicator(_ isLoading: Bool) {
        if isLoading {
            self.startAnimating()
        } else {
            self.stopAnimating()
        }
    }
}
2

There are 2 best solutions below

0
On BEST ANSWER

You can use the isAnimating property of UIActivityIndicatorView as the backing value for isLoading. You just need to make sure that you control starting/stopping the animation correctly in the setter, that will set isAnimating and as a result, isLoading will also get set correctly.

extension UIActivityIndicatorView {
    var isLoading:Bool {
        get {
            return isAnimating
        } set {
            if newValue {
                self.startAnimating()
            } else {
                self.stopAnimating()
            }
        }
    }
}
0
On

You can optimize your code by this way:

extension UIActivityIndicatorView {
    var isLoading:Bool {
        get {
            return isAnimating
        } set {
            newValue ? startAnimating() : stopAnimating()
        }
    }
}