How to disable horizontal scrolling in webView with swift?
I have a simple one webView
like:
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = "https://developer.apple.com/library/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_456"
let requestURL = NSURL(string:url)
let request = NSURLRequest(URL: requestURL!)
webView.loadRequest(request)
when i load this request in webView it loads fine, but when it is fully loaded it scrolls horizontally like this when i view it from left and right side:
I don't want to scroll it this way, and I only want it to scroll vertically, is there a way to do it in a quick internet search, but found a solution for objective-c and I am trying it quickly but not work.
Please provide me with any solution for this.
source to share
Update Swift 4
Add both of these methods to your UIViewController:
func webViewDidFinishLoad(_ webView: UIWebView) {
self.webView.scrollView.showsHorizontalScrollIndicator = false
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (scrollView.contentOffset.x > 0){
scrollView.contentOffset = CGPoint(x: 0, y: scrollView.contentOffset.y)
}
}
in the viewDidLoad method add the following lines:
webview.scrollView.delegate = self
webview.scrollView.showsHorizontalScrollIndicator = false
Now this wld is showing error in line webview.scrollView.delegate = self
, so make sure you add UIScrollViewDelegate like this
class DetailViewController: UIViewController, UIWebViewDelegate, UIScrollViewDelegate{
And the horizontal scrolling stopped :)
source to share
Sorry for answering so late, but you can do this by setting the scrollable size to scroll across the WebView after the data has finished loading by implementing the UIWebViewDelegate method.
func webViewDidFinishLoad (_ webView: UIWebView)
you can do it by doing this:
SWIFT 4:
func webViewDidFinishLoad(_ webView: UIWebView) {
let scrollableSize = CGSize(width: view.frame.size.width, height: webView.scrollView.contentSize.height)
self.webView?.scrollView.contentSize = scrollableSize
}
EDIT:
The key point here is setting the webView's scroll width to the width of your main view, which will prevent horizontal scrolling.
PS: Don't forget to accept the UIWebViewDelegate protocol
class myViewController: UIViewController,UIWebViewDelegate
and set your webView delegate to viewDidLoad
webView?.delegate = self
source to share