Skip to content

Adding Transparent Modal View Programatically– iPhone

by dkberktas on May 18th, 2010

Assuming you have a long process  taken so long that you want to show a transparent view, you can do it very easily by just adding the following method to your .m file and you will get the following transparent loading view


-(void)showLoadingView
{
	CGRect transparentViewFrame = CGRectMake(0.0, 0.0,320.0,480.0);
	transparentView = [[UIView alloc] initWithFrame:transparentViewFrame];
	transparentView.backgroundColor = [UIColor lightGrayColor];
	transparentView.alpha = 0.9;

	UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
	spinner.center = transparentView.center;
	[spinner startAnimating];

	UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 280, 320, 30)];
	messageLabel.textAlignment = UITextAlignmentCenter;
	messageLabel.text = @"please wait...";

	[transparentView addSubview:spinner];
	[transparentView addSubview:messageLabel];

	[self.view addSubview:transparentView];

	[messageLabel release];
	[spinner release];
	[transparentView release];
}

Now, you should call this function whenever needed. Let’s say you have a background process that will run while the transparent loading view is shown, below is the code to handle this situation:

-(void)myAction:(id)sender
{
	[self showLoadingView];

	[self performSelectorInBackground:@selector(myActionBackground:) withObject:sender];
}

-(void)myActionBackground:(id)sender
{
        NSAutoreleasePool *apool = [[NSAutoreleasePool alloc] init];
	//your code
        [apool release];
}

From → english, iphone, tech

7 Comments
  1. Hello,

    thank you for this nice article.
    I’ve written a small class to do this stuff because i will also disable user interaction on the navigation bar since the view is just added as subview the the navigationbar controller view.

    regards
    René

  2. Sure, that is another way of doing, thanks

  3. krishnan permalink

    How can we dismiss this Modal View?

  4. [[self parentViewController] dismissModalViewControllerAnimated:YES]; should work in your modal controller, cheers!

  5. raj permalink

    Good one bro. But what is that transparentView. is that myview

  6. raj permalink

    got it.. its the UIView.. Thanks Rene

  7. lorenzo permalink

    your code is great, but when i call the function, a small gray square appear on the top of the spinner: when i call the hidden function, all the subview do the right things, except the small square!

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS