0

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()
        }
    }
}
mandem112
  • 181
  • 14

2 Answers2

1

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()
            }
        }
    }
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
1

You can optimize your code by this way:

extension UIActivityIndicatorView {
    var isLoading:Bool {
        get {
            return isAnimating
        } set {
            newValue ? startAnimating() : stopAnimating()
        }
    }
}
Hardik Halani
  • 290
  • 2
  • 12