xcode 如何让我的 UIWebView 像 WKWebView 一样自动适应内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32573232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get my UIWebView to automatically fit content like a WKWebView does?
提问by John Hymanson
I was comparing a UIWebView and a WKWebView to see which would be best to display PDF content. I realized that WKWebView's automatically scale the content to fit the screen with no code needed, like so:
我正在比较 UIWebView 和 WKWebView 以查看哪个最适合显示 PDF 内容。我意识到 WKWebView 无需代码即可自动缩放内容以适应屏幕,如下所示:
While no matter what code I tried implementing in my UIWebView, the content just won't fit like the WKWebView does, here's what it looks like in my UIWebView:
无论我尝试在 UIWebView 中实现什么代码,内容都不会像 WKWebView 那样适合,以下是我的 UIWebView 中的样子:
and here is the code for my webView:
class WebView: UIViewController, UIWebViewDelegate, UIGestureRecognizerDelegate {
@IBOutlet var myWebView: UIWebView!
var contentUrlPassedOn: String!
override func viewDidLoad() {
super.viewDidLoad()
myWebView.delegate = self
let url: NSURL! = NSURL(string: contentUrlPassedOn)
myWebView.loadRequest(NSURLRequest(URL: url))
self.myWebView.scalesPageToFit = true
myWebView.contentMode = UIViewContentMode.ScaleAspectFit
myWebView.frame = self.view.frame
myWebView.scrollView.bouncesZoom = true
}
How can I get my UIWebView to fit content like the WKWebView?
如何让我的 UIWebView 适合 WKWebView 之类的内容?
回答by MSU_Bulldog
This is in Objective-C, but this is how I do it. If you translate it will work just fine.
这是在 Objective-C 中,但我就是这样做的。如果你翻译它会工作得很好。
[self.webView setScalesPageToFit:YES];
Perhaps, also removing this line would help do the trick. Not sure you really need it:
也许,删除这条线也有助于解决问题。不确定你真的需要它:
myWebView.contentMode = UIViewContentMode.ScaleAspectFit
Another idea is that you should set auto layout constraints to pin your UIWebView to the top and sides so that it won't resize to larger than the screen size.
另一个想法是您应该设置自动布局约束以将 UIWebView 固定到顶部和侧面,这样它就不会调整到大于屏幕尺寸。
Here is an example of how I would do this in Objective-C:
以下是我将如何在 Objective-C 中执行此操作的示例:
NSURLRequest*request=[NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
[self.webView setScalesPageToFit:YES];
self.webView.delegate = self;