Simple UIProgressHUD replacement

The private API UIProgressHUD shows an activity indicator (spinner) over a shaded round rect. Although you can use fancy and flexible replacements like MBProgressHUD, there is a simpler way if you don’t need all the extra functionality: Take a regular UIActivityIndicatorView and add a partly transparent UIView behind it.

The simplest is to subclass of UIActivityIndicatorView so you can use it like any activity indicator.

The interface file:

//  ActivityHUD.h
#import 

@interface ActivityHUD : UIActivityIndicatorView
- (ActivityHUD *)initInView:(UIView *)view;
@end

And the implementation file:

//  ActivityHUD.m
#import "ActivityHUD.h"
#import 

@implementation ActivityHUD

- (ActivityHUD *)initInView:(UIView *)view
{
    self = [super initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    if (self) {
        // add background view
        CGFloat border = self.bounds.size.height / 2;
        CGRect hudFrame = CGRectInset(self.bounds, -border, -border);
        UIView *hud = [[UIView alloc] initWithFrame:hudFrame];
        hud.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.67];
        hud.layer.cornerRadius = border;
        [self addSubview:hud];
        [self sendSubviewToBack:hud];

        // center in parent view
        [view addSubview:self];
        self.center = [self convertPoint:view.center fromView:view];
    }
    return self;
}

@end

To use, init the ActivityHUD in a view, and later call startAnimating to show it, and stopAnimating to hide.

Leave a Reply