Bo A
Bo A

Reputation: 3154

Centring a PDF in a UIWebView

Here is what my PDF looks like now when loaded in a UIWebView: (I put in a blue gradient as the UIWebView's background so you can see what I mean better).

Hi StackOverflow!

I would like to centre that so that the bottom margin is the same as the top margin. How would I do this with a PDF (not local)?

Upvotes: 2

Views: 895

Answers (2)

Bo A
Bo A

Reputation: 3154

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{
        CGFloat topInset = floor(([[self webView] frame].size.height - [[[self webView] scrollView] contentSize].height) / 2);
        [[[self webView] scrollView] setContentInset:UIEdgeInsetsMake(topInset, 0, 0, 0)];
        [[[self webView] scrollView] setContentOffset:CGPointMake(0, -topInset) animated:NO];
    });
}

This uses UIWebView's internal UIScrollView. The content size is fetched from the scroll view and is taken from the overall web view. This gives the 'extra' space. Half this and use it as a top inset and you have it centred. You do need to initially scroll the view to the correct place yourself using setContentOffset: as this seems to be set internally before we manage to set the inset. From then on everything should work.

The dispatch_after is unfortunately a requirement in iOS 8. The contentSize will be 0 if you fetch it too early after webViewDidFinishLoad:.

Upvotes: 2

ephemient
ephemient

Reputation: 204956

I have no experience with iOS, but there's a variety of ways to vertically center content in HTML.

One is to wrap your content in a table.

<style>
  html, body, table {
    height: 100%;
  }
  table {
    width: 100%;
  }
  td {
    text-align: center;
    vertical-align: middle;
  }
</style>
<table>
  <tr>
    <td>
      <object .../>
    </td>
  </tr>
</table>

Another is to apply table-like styles to elements that are already wrapping your content.

<style>
  html, body {
    height: 100%;
  }
  body {
    display: table;
    width: 100%;
  }
  center {
    display: table-cell;
    vertical-align: middle;
  }
</style>
<center>
  <object .../>
</center>

A solution with no markup is to use CSS flexible boxes.

<style>
  html, body {
    height: 100%;
  }
  body {
    display: -webkit-box;
    -webkit-box-pack: center;
    -webkit-box-align: center;
  }
</style>
<object .../>

Upvotes: 1

Related Questions