延迟加载HTML字符串到UIWebView



我在一个导航控制器中有两个视图控制器。第一个视图控制器有一个带按钮的菜单。按下这个按钮移动到第二个视图控制器,并将一个html字符串加载到UIWebView中。没有其他东西被加载到webview中,只有一个简单的NSString和html代码。实际上我是在做一个翻转卡(两个视图)其中webview是其中一个uiview的子视图。

代码如下:

containerView = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 280, 280)];
[self.view addSubview:containerView];
frontView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 280, 280)];
frontView.layer.cornerRadius = 10;
frontView.layer.masksToBounds = YES;
[frontView setBackgroundColor:[UIColor whiteColor]];
backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 280, 280)];
backView.layer.cornerRadius = 10;
backView.layer.masksToBounds = YES;
[backView setBackgroundColor:[UIColor yellowColor]];
[containerView addSubview:frontView];
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 280, 280)];
webView.scalesPageToFit = YES;
webView.userInteractionEnabled = NO;
NSString *htmlString = @"<head><meta name='viewport' content='width=device-width;'><style type='text/css'>html,body {margin: 0;padding: 0;width: 100%;height: 100%;}html {display: table;}body {display: table-cell;vertical-align: middle;padding: 20px;text-align: center;-webkit-text-size-adjust: none;}</style></head><ruby>金<rt>きん</rt></ruby><ruby>曜<rt>よう</rt></ruby><ruby>日<rt>び</rt></ruby>";
[webView loadHTMLString:htmlString baseURL:nil];
[frontView addSubview:webView];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                      action:@selector(flip)];
[self.view addGestureRecognizer:tap];

}

问题:我注意到,在我第一次按下按钮过渡到第二个视图控制器,有一个延迟看到html字符串加载到webview(它只有大约0.5 - 1秒)。如果我回到第一个视图控制器并再次点击按钮,这就不会发生了——这次是即时的。

有什么想法可能导致第一次延迟和如何避免它吗?

谢谢

加载html字符串导致延迟是一个已知的问题,但尚未修复

你可以尝试包括一个活动指示器,并显示它隐藏webview和动画,直到webview加载完全。这可以通过UIWebview的委托来实现。加载完成后,取消隐藏webview并删除活动

使用

-(void)webViewDidFinishLoad:(UIWebView *)webView ;
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;

请取消uwebview中的电话号码检测

另一个解决方案是从UIWebView切换到-[UIButton setAttributedTitle:forState:]:

[[NSAttributedString alloc] initWithData:[@"<head><meta ... </ruby>" dataUsingEncoding:NSUTF8StringEncoding]
                                 options:@{
                                           NSCharacterEncodingDocumentAttribute : @(NSUTF8StringEncoding),
                                           NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType
                                          }
                      documentAttributes:NULL
                                   error:NULL];

这仍然有点慢,但至少延迟现在在你的控制之下。此外,上述功能似乎不像WebKit那样功能完整;但是,对于您的目的应该足够好了。

最新更新