Scrollable custom view inside a UIWebView18 Feb 2015
Displaying HTML content is very easy on iOS. Just grab a
UIWebView and call
loadData:MIMEType:textEncodingName:baseURL: and enjoy the results.
This component would fit your needs 90% of the time. But in some cases, having a simple
UIWebView is not enough.
For professional reasons, I had to implement a mail reader like screen. On such a screen, there is a fixed portion on the screen that scrolls along with the portion rendering the HTML. I did not build such a view before and start thinking how I could make it.
After thinking a little bit, I first thought about implementing the fixed portion in HTML/CSS. No offense to those technologies, but they are not really my cup of tea.
I start searching on the Internet to see if someone founds a nice way implementing this without using private APIS.
Tweaking the internal
UIWebView contains a
UIScrolView. Inside this scroll view, the HTML is rendered by a Apple internal private
UIView subclass named
UIWebBrowserView. It is possible to get a reference to this subview.
To have a reference to it, simply loop over the subviews contained within the
UIScrollView of the
Once you grab it, you can use and place this view by setting its
This works great, but it has the smell of a big workaround :( Would it be possible to do it in a easier way ?
Do it thanks to the documentation
The main idea is to use the
contentInset property of the
UIScrollView of the
UIWebView to create a space at the top of the
UIWebView and fill it with some view.
It is better to see with an example. Let’s create a
UIWebView subclass named
AwesomeWebView. This will be a web view with a 100 points red view at this top.
All the work could be done in the initializer. The only thing to consider, is that adding a contentInset create a zone in the view where the coordinates are negatives.
This methods seems to be better than the first one.
You can find an example of this method on github