【问题标题】:WKWebView contentWKWeb查看内容
【发布时间】:2017-02-25 13:59:55
【问题描述】:

我正在使用 WKWebView()。我的 webView 高度的大小 = 100。 我正在 WKWebview 中加载 .gif 图像。 gif图像高度的大小= 300。我想压缩webview中的图像以适应它。

如下图所示,图片没有缩小到 webView 大小,它的原始大小是 300

如果我将 WkWebview 的 6 个给 300 ,它就正确了 .

我尝试过给予

    self.webView.contentMode = .scaleAspectFit
    self.webView.sizeToFit()
    self.webView.autoresizesSubviews = true

    self.webView.scrollView.contentInset = UIEdgeInsetsMake(0,0,0,0)
    self.webView.scrollView.isScrollEnabled = false

这是我添加 WKWebview 的方式:

self.webView = WKWebView() 
self.webView.frame = CGRect.init(x: 0, y: 64, width: self.view.frame.width, height:200) 
self.webView.autoresizingMask = .flexibleWidth 
let heightConstraint = NSLayoutConstraint(item: self.webView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200)
self.view.addSubview(self.webView) 
let filePath = Bundle.main.path(forResource:"token", ofType: "gif")
let gifData = NSData(contentsOfFile: filePath!) 
self.webView.load(gifData as! Data, mimeType: "image/gif", characterEncodingName: String(), baseURL: NSURL() as URL)

【问题讨论】:

    标签: ios swift ios10 wkwebview


    【解决方案1】:

    根据 Web 视图的配置,您可以:

    1. 设置img标签的样式,使其填充网络视图的高度:

      let htmlContent = "<img src=\"token.gif\" style=\"margin: auto; height: 100%\" />"
      
    2. 或者硬编码它的高度:

      let htmlContent = <img src=\"token.gif\" style=\"margin: auto; height: 300px\" />"
      

      或者,您可以使用字符串插值常量而不是硬编码值

      let htmlContent = "<img src=\"token.gif\" style=\"margin: auto; height: \(webViewHeight)px\" />"
      

    然后您可以将 html 加载到 web 视图中:

    webView.loadHTMLString(htmlContent, baseURL: Bundle.main.bundleURL)
    

    为了加快 Web 视图的速度,您可以内联图像数据而不是引用 gif 文件 - 有关此主题的更多信息,请参阅 Embedding Base64 Images

    【讨论】:

    • 这是我添加 WkWebview 的方式:self.webView = WKWebView() self.webView.frame = CGRect.init(x: 0, y: 64, width: self.view.frame.宽度,高度:200)self.webView.autoresizingMask = .flexibleWidth 让 heightConstraint = NSLayoutConstraint(项目:self.webView,属性:NSLayoutAttribute.height,relatedBy:NSLayoutRelation.equal,toItem:nil,属性:NSLayoutAttribute.notAnAttribute,乘数:1 , 常数: 200)
    • self.view.addSubview(self.webView) let filePath = Bundle.main.path(forResource:"token", ofType: "gif") let gifData = NSData(contentsOfFile: filePath!) self .webView.load(gifData as!Data, mimeType: "image/gif", characterEncodingName: String(), baseURL: NSURL() as URL)
    • 我需要的只是将 WKWebview 中加载的图像调整为 webview 大小。 @克里斯蒂克
    • 我尝试了您的解决方案。 “webView.loadHTMLString”没有加载任何东西。
    • 添加基本网址有效!感谢您的快速修复。唯一的问题是,一旦加载视图,webview 需要几毫秒来加载内容。
    猜你喜欢
    • 2011-09-06
    • 2017-12-20
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多