Atma
Atma

Reputation: 29805

How to center the contents of a UIWebView on the iPhone

I have a map image in a UIWebView. It default loads in the top left hand corner. I would like it to initialize in the center of the UIWebView.

Does anyone know how to do this?

Thanks!

Upvotes: 3

Views: 8058

Answers (2)

mdupls
mdupls

Reputation: 2012

Another approach is to just wrap your content in a center-aligned div tag.

<body>
<div align="center">
<!-- Your map here -->
</div>
</body>

This will work for your solution as long as you are fine with modifying the html that you pass through to the UIWebView. It doesn't require any javascript calls. The above solution, however, is needed if you'd prefer to inject style-sheet updates on demand and after the web page has loaded.

Upvotes: 2

rickharrison
rickharrison

Reputation: 4846

If the map image is the only thing in the page, is it wrapped in an html page? If it is at least wrapped in a body tag you could do the following:

NSString *bodyStyle = @"document.getElementsByTagName('body')[0].style.textAlign = 'center';";
NSString *mapStyle = @"document.getElementById('mapid').style.margin = 'auto';";

[webView stringByEvaluatingJavaScriptFromString:bodyStyle];
[webView stringByEvaluatingJavaScriptFromString:mapStyle];

Let me know how exactly your html is structured and then I can provide some more information if necessary.

Upvotes: 6

Related Questions