开发者

Center Image in UIWebView

开发者 https://www.devze.com 2022-12-22 15:59 出处:网络
Does anybody know a possibility to开发者_JAVA百科 center simple pictures within a UIWebview without using hmtl/css?

Does anybody know a possibility to开发者_JAVA百科 center simple pictures within a UIWebview without using hmtl/css? Thanks in Advance.


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.


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.


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)

}
0

精彩评论

暂无评论...
验证码 换一张
取 消