views:

291

answers:

2

Does anybody know a possibility to center simple pictures within a UIWebview without using hmtl/css? Thanks in Advance.

+1  A: 

This is not possible -- a UIWebView displays web content, nothing else. Use a UIImageView if you need to display images in your application.

Edit: Noah's comment had me look further into this, and it is possible to load local files using the loadData:MIMEType:textEncodingName:baseURL:, but I'm not sure what the centering situation is there. loadHTMLString:baseURL: is the easiest way to get this functionality, but of course you were asking how to do it without html/css.

Ian Henry
`UIWebView` can be given a URL to an image or PDF in the filesystem or elsewhere, and will display it just fine; it's an easy solution for those who don't feel like coding up a whole `UIScrollView`-based panning/zooming mechanism. `UIImageView` is by no means the only way to display images.
Noah Witherspoon
A: 

While it doesn't involve HTML, you can center images in a UIWebView in only Objective-C, kind of. There is a really direct bridge to anything you can do in JavaScript, HTML, CSS, or anything else with the WebKit API (the framework behind UIWebView and related classes). Furthermore, WebKit constructs a full document, the same as you might do with HTML, for when it presents non-HTML documents. (I can't confirm this for all types of media, but absolutely can for images.) Therefore, you can center an image loaded directly from a resource URL by executing javascript such as the following:

 var img = document.getElementsByTagName('img')[0];
 img.style.margin="auto";
 img.style.display="block"

(you can test this in Safari by loading the image then entering in the titlebar "javascript:var img = document..." where you include the full javascript on one line, and then hitting enter). Anyways, in your actual app, you just need to

 -[UIWebView stringByEvaluatingJavaScriptFromString:(NSString *)script]

(with the above script being (NSString *)script, obviously), to center the image as loaded directly from an image URL. Note: this will only work for horizontal centering, not vertical. There is probably a way to do that as well, but it is likely substantially more complicated.

Jared P