I've got a web view embedded in a scroll view, and I want the web view to be "expanded" to show all of its content, which I then want to scroll through with my scroll view.
The reason I am using a scroll View as a super view and not just using the web view as a scroll view is because I have labels above the web view that I want to include in the scrolling process (see screenshot).
So how do I make the webview resize itself so it takes up all the space it needs to show the content it contains ?
And after that, how do I make the superview (the Scroll view) resize itself according to the size of the webview?
To make this work you have to do the following steps:
UIWebView
from the nib to an outlet in your view controllerUIScrollView
, the UIView
on top of the web view (In my example I omitted all the labels in that view) and the UIWebView
.height
constraint to an outlet in your view controller.UIWebViewDelegate
webViewDidFinishLoad
set the height constraint's constant to the height of the contentSize
of the scroll view inside the web view.I won't explain the constraints in detail as you seem to already have figured them out yourself. Here is a screenshot of the constraints:
So, here is the code:
import UIKit
var MyObservationContext = 0
class ViewController: UIViewController {
@IBOutlet weak var webview: UIWebView!
@IBOutlet weak var webviewHeightConstraint: NSLayoutConstraint!
var observing = false
override func viewDidLoad() {
super.viewDidLoad()
webview.scrollView.scrollEnabled = false
webview.delegate = self
webview.loadRequest(NSURLRequest(URL: NSURL(string: "https://www.google.de/intl/de/policies/terms/regional.html")!))
}
deinit {
stopObservingHeight()
}
func startObservingHeight() {
let options = NSKeyValueObservingOptions([.New])
webview.scrollView.addObserver(self, forKeyPath: "contentSize", options: options, context: &MyObservationContext)
observing = true;
}
func stopObservingHeight() {
webview.scrollView.removeObserver(self, forKeyPath: "contentSize", context: &MyObservationContext)
observing = false
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard let keyPath = keyPath else {
super.observeValueForKeyPath(nil, ofObject: object, change: change, context: context)
return
}
switch (keyPath, context) {
case("contentSize", &MyObservationContext):
webviewHeightConstraint.constant = webview.scrollView.contentSize.height
default:
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
}
extension ViewController: UIWebViewDelegate {
func webViewDidFinishLoad(webView: UIWebView) {
print(webView.request?.URL)
webviewHeightConstraint.constant = webview.scrollView.contentSize.height
if (!observing) {
startObservingHeight()
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With