【问题标题】:How to load a UIWebView with a close button on top?如何加载顶部带有关闭按钮的 UIWebView?
【发布时间】:2010-11-27 08:54:59
【问题描述】:

我目前有以下代码从另一个视图加载 UIWebView。现在有没有我可以有一个关闭按钮?

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

}

我将加载使用 jquery mobile 构建的页面,因此页面内的关闭按钮也可以正常工作。但在导航栏上将是理想的。顺便说一句,我的应用程序确实没有有 UINavigationBar

【问题讨论】:

    标签: iphone uiwebview uinavigationcontroller jquery-mobile


    【解决方案1】:

    我会创建一个新的UIViewController 子类,比如带有笔尖的WebViewController。然后我会添加一个带有关闭按钮的UINavigationBar 和一个UIWebView。然后要显示您的网络视图控制器,您可以执行以下操作:

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

    在您的WebViewController 中您可以定义:

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

    并实现这样的东西:

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

    【讨论】:

    • 我收到 [super viewDidLoad] 错误。是否将 WebViewController 创建为新类并放置 UIView 或 NSObject 的父类?
    【解决方案2】:

    每当您加载 UIWebView 时,您都可以先在内容上运行 javascript sn-p。

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

    这只是劫持了window.close() 的正常行为,让你有机会在你的 Objective-C 中捕捉到调用。

    然后在您的 UIWebViewDelegate 中,您可以收听您选择作为关闭 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;
    }
    

    有点骇人听闻,但它允许 Web 开发人员从 HTML 内容中控制关闭按钮的外观。

    【讨论】:

    • 这可能是我在将 Javascript 混入 Objective C 本机时看到的最有用的东西之一。您今天已获得 21 分 @dillonchr。!
    猜你喜欢
    • 1970-01-01
    • 2016-11-23
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多