0

I add a UIWebView as a subview of the view. this view always has scroll even when the content of UIWebView can be shown without scroll.

  1. Is it possible not to scroll the UIWebView when the content is not shown in the screen?


Another problem is that when I scroll the UIWebView the background is dark gray

  1. is it possible to change this color?

2 Answers 2

1

Disabling scroll

When you first load your screen, in viewDidLoad write:

yourWebView.scrollView.bounces         = false
yourWebView.scrollView.isScrollEnabled = false

And implement the UIWebViewDelegate method to enable scrolling when content is fully loaded:

func webViewDidFinishLoad(_ webView: UIWebView)
{
    yourWebView.scrollView.bounces         = true
    yourWebView.scrollView.isScrollEnabled = true
}

Removing background color

You need to set the opaque property of your web-view to false:

yourWebView.backgroundColor = UIColor.clear
yourWebView.isOpaque        = false
2
  • Thanks. Removing background is ok, but when I set scroll enable in webViewDidFinish, and the content is larger than screen size, I cannot scroll. Jan 21, 2019 at 12:55
  • @FattanehTalebi: are you setting the scroll enable properties as mentioned like in the answer ? Did you set the yourWebView.delegate = self ? Are you disabling touch anywhere in your code or storyboard ? Could you please add your didFinish method here?
    – Midhun MP
    Jan 21, 2019 at 17:52
0

Use the below code, get the height of webview content in webviewDidFinishLoading and then set this height if the content height is not greater than your webview height. In the below code i assume that webview top and bottom constraints are zero from superview.

class StaticContentVC: UIViewController , UIWebViewDelegate {

@IBOutlet weak var webView  : UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    webView.delegate = self
    webView.scrollView.isScrollEnabled = false
    webView.backgroundColor = UIColor.white
    self.webView.loadRequest(URLRequest(url: YourcontentUrl as URL))

}

public func webViewDidFinishLoad(_ webView: UIWebView){
    let newSize = Float(webView.stringByEvaluatingJavaScript(from: "document.documentElement.scrollHeight") ?? "") ?? 0.0

    if CGFloat(newSize) > UIScreen.main.bounds.size.height {
        webView.scrollView.isScrollEnabled = true
    }else {
        webView.frame = CGRect(x: webView.frame.origin.x, y: webView.frame.origin.y, width: webView.frame.size.width, height: CGFloat(newSize))
        webView.scrollView.isScrollEnabled = false

    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.