How to programmatically prevent scrolling in WebView of iOS?


Disabling scrolling in WebView in iOS is very simple.

The ‘scrollView’ property of the WebView is exposed by iOS.

You will just need to disable the scrolling of the corresponding scrollView using below code.

webView.scrollView.isScrollEnabled = false

The above code will disable the scrolling on WebView.

If you were just looking to disable scrolling in web view above code would do that. If you want to know from scratch how to load WebView and disable scrolling. Follow along.

Let’s create a sample project in XCode and learn the WebView loading

Step 1 − Open Xcode → New Project → Single View Application → Let’s name it “WebViewScrollDisabling”

Step 2 − Open Main.storyboard and add a UIWebView as shown below

Step 3 − Add one IBOutlet in ViewController class for tha above add WebView name it webView.

@IBOutlet weak var webView: UIWebView!

Step 4 − Here we will load TutorialsPoint website in the webView. So in viewDidLoad method of ViewController class add following lines

webView.loadRequest(URLRequest(url: URL(string: "https://www.tutorialspoint.com/index.htm")!))

Step 5 − Run the app. You will see the TutorialsPoint website is loaded. Try to scroll the webivew. You should be able to scroll the webview as shown in the picture below.

Step 6 − Now our target is to stop this scrolling of webView. We can do this by stopping the scrolling on underlying scrollView. To do this add following line after loading the weView.

webView.scrollView.isScrollEnabled = false
After doing this your viewDidLoad method would look like this
override func viewDidLoad() {
   super.viewDidLoad()
   // Do any additional setup after loading the view, typically from a nib.
   webView.loadRequest(URLRequest(url: URL(string: "https://www.tutorialspoint.com/index.htm")!))
   webView.scrollView.isScrollEnabled = false
}

Step 7 − Now run the app. As in previous case the webView will load TutorialsPoint website. But we will not be able to scroll it. Try scrolling the webview. You will not be able to do so

raja
Published on 11-Sep-2019 11:43:30
Advertisements