3

我创建了自定义类,文件是 showBlock.h 和 showBlock.m,用于以编程方式加载 UIWebView,showBlock.m 的实现是

#import "showBlock.h"

@implementation showBlock;

@synthesize mainViewContObj;

- (void) showView {
    UIWebView *aWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
    aWebView.autoresizesSubviews = YES;
    aWebView.autoresizingMask = (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
    [aWebView setDelegate:[self mainViewContObj]];
    NSString *urlAddress = @"http://localhost/test/index.php";
    NSURL *url = [NSURL URLWithString:urlAddress];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

    [aWebView loadRequest:requestObj];

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    [[[self mainViewContObj] view] addSubview:aWebView];

}
@end

它工作正常,并加载带有 html 内容的 index.php 文件,但我想在 safari 浏览器中打开这个 html 文件的链接,我需要为此做些什么?

4

3 回答 3

11

您需要在 ShowBlock.m 中添加下面的委托方法实现

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType {
    // This practically disables web navigation from the webView.
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        [[UIApplication sharedApplication] openURL:[request URL]];
        return FALSE;
    }
    return TRUE;
}
于 2012-11-08T15:22:53.350 回答
1

实现UIWebViewDelegate协议并设置aWebView.delegate = self.

然后实施

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;

单击链接时将调用此方法。从请求中获取 URL。

使用下面的代码在 safari 中打开一个链接:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString: @\"http://www.google.com"]];
于 2012-11-08T15:19:04.687 回答
1

在您UIWebView委托中,定义webView:shouldStartLoadWithRequest方法:

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {

    if ([[request URL] checkCondition]) 
       [[UIApplication sharedApplication] openURL:[request URL]];
        return NO;
    }
    return YES;

}

checkCondition是一种检查 URL 是否应由 safari 打开的方法(您可以根据域或其他内容进行检查)。在最简单的情况下,始终调用openURL(删除if

于 2012-11-08T15:21:05.393 回答