UIActivityIndicatorView を使って画面中央にインジケーターを表示してみた

Web API を呼び出している間、画面に何のデータも表示しないってのはユーザーを不安にさせるので、画面中央にインジケーターを表示することにした。標準で UIActivityIndicatorViwe というシンプルなインジケーターが提供されているので、こいつを使ってみる。

最初、StoryBoard 上で UIActivityIndicatorViwe を張り付けたんだけど、画面中央に表示されるようにコードで位置を調節したはずなのに、全然中央に表示されなかった。画面右端に追いやられてしまう…。UITableView とかと同じレイヤーにあるんだろうか?

試しに透明の UIView をかぶせて、その UIView に UIActivityIndicatorViwe を追加してみたら、期待通りに画面中央に表示できた。

...

@interface DetailViewController ()
@property (nonatomic, strong) UIView *loadingView;
@property (nonatomic, strong) UIActivityIndicatorView *indicator;
@end


@implementation DetailViewController

...

- (void)showIndicator
{
    self.loadingView = [[UIView alloc] initWithFrame:self.navigationController.view.bounds];
    self.loadingView.backgroundColor = [UIColor clearColor];
    [self.navigationController.view addSubview:self.loadingView];
    
    self.indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.indicator.color = [UIColor blackColor];
    self.indicator.center = self.loadingView.center;
    [self.loadingView addSubview:self.indicator];
    
    [self.indicator startAnimating];
}

- (void)hideIndicator
{
    [self.indicator stopAnimating];
    [self.indicator removeFromSuperview];
    [self.loadingView removeFromSuperview];
    self.indicator = nil;
    self.loadingView = nil;
}

...

@end