在Swift中从本地文件编辑和加载HTML

问题描述 投票:1回答:2

我的项目包中存储了一个.html文件。当我在WebView。(UIWebview / WKWebview)中加载数据时,数据被加载但其中的表结构不可见。表格边框,列,行。这些值只是浮动的。在Chrome浏览器中,它可以正常打开

let myURL = Bundle.main.url(forResource: "prescription", withExtension: "html")
    let myURLRequest:URLRequest = URLRequest(url: myURL!)
    webView.loadRequest(myURLRequest)

Chrome浏览器:This is how it looks in browser

iOS App UIWebView:

This is how it looks in UIWebview

Html页面响应适合任何大小,但我无法正确加载UIWebview作为Web。我需要在本地存储文件,因为我需要更改其值并在webview上显示。

html ios swift uiwebview wkwebview
2个回答
1
投票

找到解决方案:如果您正在应用一些本地css,其路径在HTML文件中。即

  1. 将css文件“my Default.css”添加到xcode项目目录中。
  2. 将HTML转换为字符串,并使用本地路径替换HTML文件中的css路径。 :
  3. 使用基本URL将HTML内容加载到UIWebView。 (提供本地文件路径作为baseUrl很重要) webView = UIWebView() let pathToInvoiceHTMLTemplate = Bundle.main.path(forResource: "presc", ofType: "html") let pathToHTMLCSS = Bundle.main.path(forResource: "myDefault", ofType: "css") do { var strHTMLContent = try String(contentsOfFile: pathToInvoiceHTMLTemplate!) strHTMLContent = strHTMLContent.replacingOccurrences(of: "./assets/stylesheets/myDefault.css", with: pathToHTMLCSS!) let pdfURL = URL(fileURLWithPath: pathToInvoiceHTMLTemplate!) webView.loadHTMLString(strHTMLContent, baseURL: pdfURL) }catch let err{ print(err) }

0
投票

将本地内容加载到WKWebView时,你应该使用loadHTMLString(_:baseURL:)而不是loadRequest。第一个函数允许您提供基本URL,您也可以将其指向包中 - 因此您显然需要将所有相关文件添加到应用程序包中。

guard let indexPath = Bundle.main.path(forResource: "index", ofType: "html"),
   let content =  try String(contentsOfFile: indexPath, encoding: .utf8),
   let baseUrl = URL(fileURLWithPath: indexPath) else {
        // Error handling
   }
webView.loadHTMLString(content, baseURL: baseUrl)
© www.soinside.com 2019 - 2024. All rights reserved.