我正在尝试在运行iOS 8及更高版本时,用WKWebView实例替换动态分配的UIWebView实例,并且我找不到确定WKWebView内容大小的方法。
我的网页视图嵌入在较大的UIScrollView容器中,因此我需要确定网页视图的理想大小。这将使我能够修改它的框架以显示所有HTML内容,而无需在网页视图内滚动,并且我将能够为滚动视图容器设置正确的高度(通过设置scrollview.contentSize)。
我已经尝试了sizeToFit和sizeThatFits,但都没有成功。以下是创建WKWebView实例并将其添加到容器滚动视图的代码:
// 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。