How to load UIWebView using the close button on top?

I currently have the following code that loads a UIWebView from another view. Do I have a close button now?

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UIWebView *webView=[[UIWebView alloc] initWithFrame:CGRectMake(0,0,320,480)]; [self.view addSubview:webView]; NSURLRequest *urlRequest; NSURL *urlforWebView; urlforWebView=[NSURL URLWithString:@"http://www.google.com"]; urlRequest=[NSURLRequest requestWithURL:urlforWebView]; [webView loadRequest:urlRequest]; } 

I'm going to load a page created using jquery mobile, so the close button inside the page will also work fine. But the navigation bar would be perfect. Btw, my application does not have a UINavigationBar

+4
source share
2 answers

I would create a new subclass of the UIViewController class, say WebViewController using nib. Then I will add a UINavigationBar with a close button and a UIWebView . Then, to show your webview controller, you can do something like:

 WebViewController *webViewController = [[WebViewController alloc] init]; webViewController.loadURL = [NSURL URLWithString:@"http://www.google.com"]; [self presentModalViewController:webViewController animated:YES]; [webViewController release]; 

In WebViewController you can define:

 @property (nonatomic, retain) IBOutlet UIWebView *webView; @property (nonatomic, retain) NSURL *loadURL; - (IBAction)close:(id)sender; 

and implement something like this:

 - (void)viewDidLoad { [super viewDidLoad] NSURLRequest *urlRequest = [NSURLRequest requestWithURL:self.loadURL]; [self.webView loadRequest:urlRequest]; } - (IBAction)close:(id)sender { [self dismissModalViewControllerAnimated:YES]; } 
+10
source

Whenever you load a UIWebView, you can first run a javascript fragment in the content.

 [webView stringByEvaluatingJavaScriptFromString:@"window.close = function() { window.location = 'app://close-webview'; };"]; 

It just captures the normal behavior of window.close() and gives you the ability to catch a call in your Objective-C.

Then in your UIWebViewDelegate you can listen to everything that you have chosen as the private URL.

 - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if([request.URL.absoluteString isEqualToString:@"app://close-webview"]) { webView.hidden = YES; // or whatever you want to do to remove the UIWebView... return NO; } return YES; } 

A bit hacky, but this will allow the web developer to control the appearance of the close button from the HTML content.

+5
source

All Articles