Question

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?

Was it helpful?

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];

OTHER TIPS

WORKS IOS 7+

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Loading data" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];

UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[indicator startAnimating];

[alertView setValue:indicator forKey:@"accessoryView"];
[alertView show];

and to dismiss it

[alertView dismissWithClickedButtonIndex:0 animated:YES];
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];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top