Search code examples
iosswiftuiactivityindicatorview

Custom image with rotation in activity indicator for iPhone application in swift


I want my company logo as in activity indicator with rotation in my iPhone application. I am working on swift. Can anyone suggest me some third party library other than SVProgressHUD as this is not providing any custom image rotation.

If someone can suggest an custom code then also it will be appreciated.


Solution

  • You can try something like this:

    final class MyActivityIndicator: UIImageView {
    
        override func startAnimating() {
            isHidden = false
            rotate()
        }
    
        override func stopAnimating() {
            isHidden = true
            removeRotation()
        }
    
        private func rotate() {
            let rotation = CABasicAnimation(keyPath: "transform.rotation.z")
            rotation.toValue = NSNumber(value: Double.pi * 2)
            rotation.duration = 1
            rotation.isCumulative = true
            rotation.repeatCount = Float.greatestFiniteMagnitude
            layer.add(rotation, forKey: "rotationAnimation")
        }
    
        private func removeRotation() {
            layer.removeAnimation(forKey: "rotationAnimation")
        }
    }
    

    Usage:

    let activityIndicator = MyActivityIndicator(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    activityIndicator.image = UIImage(named: "TOU IMAGE")
    view.addSubview(activityIndicator)
    activityIndicator.startAnimating()