How to load a UIWebView with a close button on top?

穿精又带淫゛_ 提交于 2019-12-05 01:18:09

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/4290824/how-to-load-a-uiwebview-with-a-close-button-on-top

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!