如何确定 UIWebView 的内容大小? [英] How to determine the content size of a UIWebView?

查看:36
本文介绍了如何确定 UIWebView 的内容大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有不同(单页)内容的 UIWebView.我想找出内容的 CGSize 以适当地调整我的父视图的大小.显而易见的 -sizeThatFits: 不幸的是只返回 webView 的当前帧大小.

I have a UIWebView with different (single page) content. I'd like to find out the CGSize of the content to resize my parent views appropriately. The obvious -sizeThatFits: unfortunately just returns the current frame size of the webView.

推荐答案

结果证明我第一次使用 -sizeThatFits: 的猜测并没有完全错误.它似乎有效,但前提是在发送 -sizeThatFits: 之前将 webView 的框架设置为最小尺寸.之后,我们可以通过拟合尺寸来纠正错误的框架尺寸.这听起来很可怕,但实际上并没有那么糟糕.由于我们在彼此之后立即进行两个框架更改,因此视图不会更新并且不会闪烁.

It turned out that my first guess using -sizeThatFits: was not completely wrong. It seems to work, but only if the frame of the webView is set to a minimal size prior to sending -sizeThatFits:. After that we can correct the wrong frame size by the fitting size. This sounds terrible but it's actually not that bad. Since we do both frame changes right after each other, the view isn't updated and doesn't flicker.

当然要等到内容加载完毕,所以我们把代码放到了-webViewDidFinishLoad:委托方法中.

Of course, we have to wait until the content has been loaded, so we put the code into the -webViewDidFinishLoad: delegate method.

Obj-C

- (void)webViewDidFinishLoad:(UIWebView *)aWebView {
    CGRect frame = aWebView.frame;
    frame.size.height = 1;
    aWebView.frame = frame;
    CGSize fittingSize = [aWebView sizeThatFits:CGSizeZero];
    frame.size = fittingSize;
    aWebView.frame = frame;

    NSLog(@"size: %f, %f", fittingSize.width, fittingSize.height);
}

Swift 4.x

func webViewDidFinishLoad(_ webView: UIWebView) {
    var frame = webView.frame
    frame.size.height = 1
    webView.frame = frame
    let fittingSize = webView.sizeThatFits(CGSize.init(width: 0, height: 0))
    frame.size = fittingSize
    webView.frame = frame
}

我应该指出有 另一种方法(感谢@GregInYEG)使用JavaScript.不确定哪种解决方案效果更好.

I should point out there's another approach (thanks @GregInYEG) using JavaScript. Not sure which solution performs better.

在两个 hacky 解决方案中,我更喜欢这个.

Of two hacky solutions I like this one better.

这篇关于如何确定 UIWebView 的内容大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆