i have a scrollview and want to add multiple webviews dynamically into it. need to get height of webview. i have used below code. but it does't work always.some times showing wrong height. func webViewDidFinishLoad(aWebView: UIWebView) {
let screenSize = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
var frame = aWebView.frame
frame.size.height = 1
frame.size.width = screenSize.width
aWebView.frame = frame
let fittingSize = aWebView.sizeThatFits(CGSizeZero)
frame.size = fittingSize
aWebView.frame = frame
}
This is a really good question, fitting web views to their content has interesting applications, such as showing an info windows on a map using a web view that fits to its content.
Here is a solution using
WKWebView
that begins by creating a 1-by-1px size web view, loading its content, and querying the web view to find its content size before updating the web view frame size accordingly. Slightly hacky but seems to be the only way.My sample HTML file (
index.html
):Note: You should try to use the
WKWebView
instead of theUIWebView
if possible. AUIWebView
solution may be possible, but I don't think it's worthy of the time and effort when theWKWebView
should fit your needs better.