Tibbe Tibbe - 1 year ago 177
iOS Question

Activity indicator with custom image

I am loading a

and in the meantime I wan't to show a blank page with thisspinner activity indicator spinning (siri activity indicator). From what I have understand you can not change the image, but can't I use that image and create an animation with it rotating 360° and looping? Or will that drain the battery?

something like this?:

- (void)webViewDidStartLoad:(UIWebView *)webView {
//set up animation
[self.view addSubview:self.loadingImage];
//start animation

- (void)webViewDidFinishLoad:(UIWebView *)webView
//stop animation
[self.loadingImage removeFromSuperview];

What should I do?

Thanks in advance!

Answer Source

Most of this is found in Stack Overflow. Let me summarize:

Create an UIImageView which will serve as an activity indicator (inside storyboard scene, NIB, code ... wherever you wish). Let's call it _activityIndicatorImage

Load your image: _activityIndicatorImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"activity_indicator"]];

You need to use animation to rotate it. Here is the method I use:

+ (void)rotateLayerInfinite:(CALayer *)layer
    CABasicAnimation *rotation;
    rotation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    rotation.fromValue = [NSNumber numberWithFloat:0];
    rotation.toValue = [NSNumber numberWithFloat:(2 * M_PI)];
    rotation.duration = 0.7f; // Speed
    rotation.repeatCount = HUGE_VALF; // Repeat forever. Can be a finite number.
    [layer removeAllAnimations];
    [layer addAnimation:rotation forKey:@"Spin"];

Inside my layoutSubviews method I initiate rotation. You could place this in your webViewDidStartLoad and webViewDidFinishLoad if this is better for your case:

- (void)layoutSubviews
    [super layoutSubviews];

    // some other code 

    [Utils rotateLayerInfinite:_activityIndicatorImage.layer];

You could always always stop rotation using [_activityIndicatorImage.layer removeAllAnimations];

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download