iPhone SDK UIWebView Alert
I found myself needing a quick way to show a simple web page in my apps. I created this custom UIAlertView to do just that. Code after the jump.
@interface WebAlert : UIAlertView{ @private UIWebView *alertWeb; UIActivityIndicatorView *activityIndicator; } - (void) loadURL:(NSString *) url; @end #import "WebAlert.h" @implementation WebAlert - (void) loadURL:(NSString *) url { alertWeb.hidden = YES; [alertWeb loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]]; } - (id)initWithFrame:(CGRect)frame { if ((self = [super initWithFrame:frame])) { alertWeb = [[[UIWebView alloc] initWithFrame:CGRectZero] retain]; alertWeb.delegate = self; [self addSubview:alertWeb]; } return self; } // UIWebView Delegate - (void) webViewDidStartLoad:(UIWebView *) webView { if(activityIndicator == nil) { activityIndicator = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] retain]; [self addSubview:activityIndicator]; } [activityIndicator startAnimating]; } - (void)webViewDidFinishLoad:(UIWebView *)webView { [activityIndicator stopAnimating]; [self performSelector:@selector(showAboutWebView) withObject:nil afterDelay:.2]; } - (void) showAboutWebView { alertWeb.hidden = NO; } - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if (navigationType == UIWebViewNavigationTypeLinkClicked) { [[UIApplication sharedApplication] openURL:request.URL]; return false; } return true; } - (void)setFrame:(CGRect)rect { [super setFrame:CGRectMake(0, 0, rect.size.width, 275)]; self.center = CGPointMake(480/2, 320/2); } - (void)layoutSubviews { CGRect buttonFrame = CGRectMake(0, 0, 0, 0); for (UIView *view in self.subviews) { if ([[[view class] description] isEqualToString:@"UIThreePartButton"]) { view.frame = CGRectMake(view.frame.origin.x, self.bounds.size.height - view.frame.size.height - 12, view.frame.size.width, view.frame.size.height); if(buttonFrame.size.width == 0) buttonFrame = view.frame; } } int webHeight = 160; alertWeb.frame = CGRectMake(buttonFrame.origin.x+1, buttonFrame.origin.y - (webHeight + 10), 260, webHeight); float activeX = (alertWeb.frame.origin.x + (alertWeb.frame.size.width/2)) - (activityIndicator.frame.size.width/2); float activeY = (alertWeb.frame.origin.y + (alertWeb.frame.size.height/2)) - (activityIndicator.frame.size.height/2); activityIndicator.frame = CGRectMake(activeX, activeY, activityIndicator.frame.size.width, activityIndicator.frame.size.height); } - (void) dealloc { [activityIndicator release]; alertWeb.delegate = nil; [alertWeb stopLoading]; [alertWeb release]; [super dealloc]; } @end