Mike Mike - 3 months ago 16
iOS Question

Adding subviews to UIWebView's internal scrollview

My aim is to add a Google DFP Banner view (banner ad) to a page of HTML and have it scroll with the HTML on an iPad.

The HTML is displayed using a

UIWebView
as is normal on iOS.

How can I sit the DFP Banner View (inherits from
UIView
) with the content so that it scrolls as if it was part of the page?

What I have done so far:


  • UIWebView
    has a
    *scrollview
    property.

  • Traverse subviews of the
    webview.scrollview
    .

  • For each view, adjust the frame to move them down
    by height of the banner, and make them smaller by the same amount.

  • Insert the banner view into the web view's
    scrollview
    .

    for (UIView *view in self.webview.scrollView.subviews) {
    CGRect frame = view.frame;
    frame.origin.y += bannerAdvertsHeight;
    frame.size.height -= bannerAdvertsHeight;
    view.frame = frame;
    }

    [self.webview.scrollView addSubview:self.dfpBannerView];



I don't have access to an iPad currently, but this is working on the simulator. I'm not sure if it's a 'good' solution. Please tell me if you think there are any issues with my approach.

Answer

Here's the view hierarchy of a UIWebView:

(gdb) po [webView recursiveDescription]
<UIWebView: 0x68220e0; frame = (0 0; 320 460); >
| <UIScrollView: 0x4b2bee0; frame = (0 0; 320 460); >
|    | <UIImageView: 0x4b2dca0; frame = (0 0; 54 54); >
|    | <UIImageView: 0x4b2da20; frame = (0 0; 54 54); >
|    | <UIImageView: 0x4b2d9c0; frame = (0 0; 54 54); >
|    | <UIImageView: 0x4b12030; frame = (0 0; 54 54) >
|    | <UIImageView: 0x4b11fd0; frame = (-14.5 14.5; 30 1); >
|    | <UIImageView: 0x4b11f70; frame = (-14.5 14.5; 30 1); >
|    | <UIImageView: 0x4b11f10; frame = (0 0; 1 30); >
|    | <UIImageView: 0x4b11eb0; frame = (0 0; 1 30); >
|    | <UIImageView: 0x4b11e50; frame = (0 430; 320 30); >
|    | <UIImageView: 0x4b2d0c0; frame = (0 0; 320 30);  >
|    | <UIWebBrowserView: 0x6005800; frame = (0 0; 320 460); >

Looking at the hierarchy, you should probably add your banner to UIWebBrowserView, or if not, on top of it:

for (id view in self.webview.scrollView.subviews) {
    if (![view isKindOfClass:[UIImageView class]]) {
        CGRect frame = view.frame;
        frame.origin.y += bannerAdvertsHeight;
        frame.size.height -= bannerAdvertsHeight;
        view.frame = frame;
    }
} 
[self.webview.scrollView addSubview:self.dfpBannerView];

Although this is kind of a hack so you might get into trouble later on in later iOS updates.