Luda
Luda

Reputation: 7068

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.

Upvotes: 11

Views: 4698

Answers (2)

MarkHim
MarkHim

Reputation: 5776

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

Upvotes: 5

Tapani
Tapani

Reputation: 3231

You basically have a scrollview inside a scrollview. How do you suppose that would work? I would add the labels to the HTML in the WebView. Don't see any reason why they need to be native.

Alternatively, you could try to add the labels to the UIWebView's UIScrollView. That's it's first subview. Not sure if you need to adjust the scrollview insets. Injecting html probably would work more reliably.

Upvotes: 0

Related Questions