【问题标题】:Embed a UIwebView in a UITableViewCell在 UITableViewCell 中嵌入 UIwebView
【发布时间】:2017-07-21 06:41:31
【问题描述】:

我想在 UITableViewCell 中嵌入 UIWebView。但是也有一些问题:

1,我在方法中设置单元格的数据库:

    (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell * cell = [tableView 
    dequeueReusableCellWithIdentifier:cellIdenWebViewIntro 
    forIndexPath:indexPath];

    PlayListModel * model = [PlayListModel new];
    cell.model = model;
    return cell;

    }

在单元格中,我设置 webView 并在 setModel 方法中发送 url 请求:

- (void)setModel:(PlayListModel *)model{
    _model = model;

    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://temp url"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    [self.webView loadRequest:request];
}

这是配置单元的一种非常正常的方式。但是当tableView向下滚动并滚动回webViewCell时,系统再次调用(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath,所以webView会一次又一次地发送url请求。所以有办法缓存webView的HTML内容。如果用户没有弹出当前视图控制器,我将为 webView 重用 HTML,但不会多次发送请求。

p.s 我在创建 NSURLRequest 时已经设置了缓存策略,但是它不起作用。

【问题讨论】:

    标签: ios objective-c uitableview


    【解决方案1】:

    是的,这是意料之中的。 TableView 将在滚动时调用cellForRowAtIndexPath 方法。

    您可以做的是下载该URLHTML 内容并将其存储。因此,当单元格重新加载时,您可以检查是否有该 HTML 的内容 URL 然后从存储的变量或数据库中加载它。

    要下载文件,请查看here

    【讨论】:

    • 对了,有没有办法下载HTML内容?
    【解决方案2】:

    还有另一种通过 javascript 下载 HTML 内容的方法。

    // DidFinishLoad
    -(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
    {
        NSString *getHTMLJSCode = @"document.getElementsByTagName('html')[0].innerHTML";
        [wkWebView evaluateJavaScript:getHTMLJSCode completionHandler:^(id _Nullable content, NSError * _Nullable error)
         {
             if (error) {
                 NSLog(@"Error: %@",error);
                 return;
             }
    
             NSLog(@"Content: %@",content);
             self.HTMLSourceCode = content; // cache 
         }];
    }
    

    您可以在第一次加载时加载请求然后缓存它。

    if (HTMLSourceCode) {
        // To load cached webpage.
        [wkWebView loadHTMLString:HTMLSourceCode baseURL:[NSURL URLWithString:_urlString]];
    }
    else {
        //...
        [wkWebView loadWithURLRequest:request]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      • 2012-01-20
      • 2015-11-15
      • 1970-01-01
      • 2013-11-07
      • 1970-01-01
      • 2015-01-01
      相关资源
      最近更新 更多