How to Programmatically Scroll iOS Wkwebview, Swift 4

How to Programmatically Scroll iOS WKWebView, swift 4

This will also account for the possible horizontal offset of the origin of the scrollView:

var scrollPoint = self.view.convert(CGPoint(x: 0, y: 0), to: webView.scrollView)
scrollPoint = CGPoint(x: scrollPoint.x, y: webView.scrollView.contentSize.height - webView.frame.size.height)
webView.scrollView.setContentOffset(scrollPoint, animated: true)

Scrolling to the bottom of the WKWebView programmatically doesn't work

Found the solution, removed the code I used and switched it to the following one:

    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("var scrollingElement = (document.scrollingElement || document.body); scrollingElement.scrollTop = scrollingElement.scrollHeight;")
}

Scroll on button click a ScrollView/WKWebView, Swift

Here is a simplified demo of possible approach. Tested with Xcode 12 / iOS 14.

struct DemoWebView : UIViewRepresentable {
let text: String
@Binding var scrollToBottom: Bool

func makeUIView(context: Context) -> WKWebView {
let webview = WKWebView()
webview.loadHTMLString(text, baseURL: nil)
return webview
}

func updateUIView(_ webview: WKWebView, context: Context) {
if scrollToBottom {
let point = CGPoint(x: 0, y: webview.scrollView.contentSize.height - webview.frame.size.height)
webview.scrollView.setContentOffset(point, animated: true)
DispatchQueue.main.async {
self.scrollToBottom = false // turn it back for reuse
}
}
}
}

and usage like

@State private var scroll = false

var body: some View {
VStack {
Button("Bottom") { self.scroll = true }
DemoWebView(text: self.htmlText, scrollToBottom: $scroll)
}
}

Scroll to bottom of webview programmatically with swift

You can use scrollView property of UIWebView for that.

func webViewDidFinishLoad(_ webView: UIWebView) {

let scrollPoint = CGPoint(x: 0, y: webView.scrollView.contentSize.height - webView.frame.size.height)
webView.scrollView.setContentOffset(scrollPoint, animated: true)//Set false if you doesn't want animation
}

Note: Don't forgot to set delegate of your webView.

How can I scroll programmatically to the bottom in a UIWebView?

This is fairly simple. First, you'll need to obtain height of the webpage:

NSInteger height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"] intValue];

Now you have the height of the document stored in the height variable. To scroll to bottom you have to use javascript again:

NSString* javascript = [NSString stringWithFormat:@"window.scrollBy(0, %d);", height];   
[webView stringByEvaluatingJavaScriptFromString:javascript];

Of course you need to call them in proper moment. That is

– webViewDidFinishLoad:(UIWebView *)webView

method of your webview delegate.



Related Topics



Leave a reply



Submit