Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWIFT - HTML scrolling events in a WKWebView that's inside a ScrollView

I have a web page for testing purposes (https://storage.googleapis.com/htmltestingbucket/nested_scroll_helper.html) that just prints a counter of the scroll event the html has caught in a fixed header

When the WKWebView is the only scroll-able element in the fragment everything is fine and the WebView sends the scroll events to the page

If I want to add native elements above and below the WebView then things get much more complex.

UIScrollView  
    UILabel
    WKWebView
    UILabel

I know it's not good to have a WebView inside a ScrollView but I have to provide a single scrolling experience with hybrid content and proper scrolling events in the html document. I found plenty of questions on the matter but I was not able to create a full end-to-end solution.

like image 623
Luda Avatar asked Feb 02 '16 14:02

Luda


1 Answers

Update: Okay took me a while to understand what you're trying to do.

I know you would like to keep the outer scrollView, but I'm pretty sure it's not possible to achieve what you want to do (only way could be if you set the outerScrollView.delegate = webView - but didn't work for me when I tried)

I think the best solution would be:

  1. remove your outer scrollView
  2. set the contentInsets for your webView to whatever height on top and bottom you need. E.g. for 100pt : webView.contentInset = UIEdgeInsetsMake(100,0,100,0);
  3. Add your UIElements as subView to your UIWebView instead of the UIScrollView (basically into the free space you created with your contentInsets)

Previously (Other way around):

  1. set up a height constraint of your UIWebView
  2. store the height constraint as IBOutlet in your UIViewController
  3. set webView.scrollView.scrollEnabled = NO; in your viewDidLoad or the storyboard
  4. as soon as the webView is loaded, extract its content height webView.scrollView.contentSize.height
  5. update the UIWebView height constraint with the value of its content height viaself.webViewContentHeightConstraint.constant = webView.scrollView.contentSize.height
  6. call [self.scrollView layoutIfNeeded]; to make sure your view gets rendered again

Don`t forget to do steps 4 & 5 whenever the webView did finish loading content

enter image description here

like image 113
MarkHim Avatar answered Nov 02 '22 00:11

MarkHim