Simon D.
Simon D.

Reputation: 525

Center Image in UIWebView

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

Upvotes: 1

Views: 4138

Answers (3)

Hasan Saral
Hasan Saral

Reputation: 1

Swift First action = webView.navigationDelegate = self

and

func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {

        let cssString = "html,body { height: 100%; display: flex; align-items: center; justify-content: center; }"
        let jsString = "var style = document.createElement('style'); style.innerHTML = '\(cssString)'; document.head.appendChild(style);"
        webView.evaluateJavaScript(jsString, completionHandler: nil)

}

Upvotes: 0

Ian Henry
Ian Henry

Reputation: 22433

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.

Upvotes: 1

Jared Pochtar
Jared Pochtar

Reputation: 4985

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.

Upvotes: 1

Related Questions