我正在尝试在iOS 8及更高版本下运行时,用WKWebView实例替换动态分配的UIWebView实例,但找不到确定WKWebView内容大小的方法。
我的Web视图嵌入在较大的UIScrollView容器中,因此,我需要确定Web视图的理想大小。这将允许我修改其框架以显示其所有HTML内容,而无需在Web视图内滚动,而且我将能够为滚动视图容器设置正确的高度(通过设置scrollview.contentSize)。
我尝试过sizeToFit和sizeThatFits没有成功。这是我的代码,该代码创建WKWebView实例并将其添加到容器scrollview中:
// self.view is a UIScrollView sized to something like 320.0 x 400.0.
CGRect wvFrame = CGRectMake(0, 0, self.view.frame.size.width, 100.0);
self.mWebView = [[[WKWebView alloc] initWithFrame:wvFrame] autorelease];
self.mWebView.navigationDelegate = self;
self.mWebView.scrollView.bounces = NO;
self.mWebView.scrollView.scrollEnabled = NO;
NSString *s = ... // Load s from a Core Data field.
[self.mWebView loadHTMLString:s baseURL:nil];
[self.view addSubview:self.mWebView];
这是一个实验性的didFinishNavigation方法:
- (void)webView:(WKWebView *)aWebView
didFinishNavigation:(WKNavigation *)aNavigation
{
CGRect wvFrame = aWebView.frame;
NSLog(@"original wvFrame: %@\n", NSStringFromCGRect(wvFrame));
[aWebView sizeToFit];
NSLog(@"wvFrame after sizeToFit: %@\n", NSStringFromCGRect(wvFrame));
wvFrame.size.height = 1.0;
aWebView.frame = wvFrame;
CGSize sz = [aWebView sizeThatFits:CGSizeZero];
NSLog(@"sizeThatFits A: %@\n", NSStringFromCGSize(sz));
sz = CGSizeMake(wvFrame.size.width, 0.0);
sz = [aWebView sizeThatFits:sz];
NSLog(@"sizeThatFits B: %@\n", NSStringFromCGSize(sz));
}
这是生成的输出:
2014-12-16 17:29:38.055 App[...] original wvFrame: {{0, 0}, {320, 100}}
2014-12-16 17:29:38.055 App[...] wvFrame after sizeToFit: {{0, 0}, {320, 100}}
2014-12-16 17:29:38.056 App[...] wvFrame after sizeThatFits A: {320, 1}
2014-12-16 17:29:38.056 App[...] wvFrame after sizeThatFits B: {320, 1}
sizeToFit调用无效,并且sizeThatFits始终返回高度1。