Question

I currently have the following code that loads a UIWebView from another View. Now is there anyway I can have a close button?

- (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 am going to load a page built using jquery mobile, so a close button inside the page would also work fine. But on a navigation bar would be ideal. Btw, my application does not have a UINavigationBar

Was it helpful?

Solution

I would create a new sub class of UIViewController, say WebViewController with a nib. Then I would add an UINavigationBar with a close button and an UIWebView. Then to show your web view 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 your 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];
}

OTHER TIPS

Whenever you load the UIWebView, you could run a javascript snippet on the content first.

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

That just hijacks the normal behavior of window.close() and gives you chance to catch the call in your Objective-C.

Then in your UIWebViewDelegate you could listen for whatever you chose as the close 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 hackish, but it would allow the web developer to control the look and feel of the close button from within the HTML content.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top