'Center Image in UIWebView
Does anybody know a possibility to center simple pictures within a UIWebview without using hmtl/css? Thanks in Advance.
Solution 1:[1]
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.
Solution 2:[2]
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)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jared Pochtar |
| Solution 2 | Hasan Saral |
