iOS Gray Out View and Add an Activity Indicator in the Center

02.24.2015

Recently, I needed to figure out a way to gray out the screen with an activity indicator in the center in a scrollable table view.

This was the simplest way I’ve found to do that:

In the implementation file, create a class property to store the Y scroll offset.

@interface PhotosTableViewController () <UIPopoverControllerDelegate>
@property (nonatomic) CGFloat scrollY;
@end

Initialize the scrollY offset in initWithNibName.

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        self.scrollY = 0.0;
    }
    return self;
}

Then implement the scrollViewDidScroll method that is part of the UIScrollViewDelegate protocol. We will capture the offset anytime the user scrolls.

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
     self.scrollY = scrollView.contentOffset.y;
}

Then create the container view and indicator view. We set the Y origin of the container to the current scroll position.

CGRect maskFrame = CGRectMake(self.view.frame.origin.x, self.scrollY, self.view.frame.size.width, self.view.frame.size.height);
    
UIView *mask = [[UIView alloc] initWithFrame:maskFrame];
    
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    
indicator.frame = self.view.frame;

[indicator startAnimating];
    
[mask addSubview:indicator];
    
[mask setBackgroundColor:[UIColor colorWithWhite:0.0 alpha:0.78]];
    
[self.view addSubview:mask];

And the code to remove the view:

 [mask removeFromSuperview];

Sources

http://stackoverflow.com/questions/1431021/gray-out-view-in-iphone-how