iosuiactivityindicatorviewalertview

How to add UIActivityIndicatorView at center of UIAlertView?


As the title, I want to add an UIActivityIndicatorView instance at center of an UIAlertView instance. Here is my code:

    alertView  = [[UIAlertView alloc]initWithTitle:@"Processing" message:@"" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];

    CGRect screenRect = [[UIScreen mainScreen] bounds];
indicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(screenRect.size.width/2, screenRect.size.height/2,50,50)];
[alertView addSubview: indicator];
[indicator startAnimating];
[alertView show];

What I see is just the alertView. Did I make any mistake?


Solution

  • You have forgotten to take into account the indicator's width and height, when setting it's x and y position in the alertview frame.

    indicator = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake(roundf((screenRect.size.width - 50) / 2), roundf((screenRect.size.height - 50) / 2),50,50)];
    

    EDIT: This is the exact one I typically use: (don't forget to release things, etc)

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Loading..." message: nil delegate:self cancelButtonTitle: nil otherButtonTitles: nil];
    UIActivityIndicatorView *progress= [[UIActivityIndicatorView alloc] initWithFrame: CGRectMake(125, 50, 30, 30)];
        progress.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    [alert addSubview: progress];
    [progress startAnimating];
    [alert show];