【问题标题】:How can I load the CSS file with HTML in Swift 3?如何在 Swift 3 中加载带有 HTML 的 CSS 文件?
【发布时间】:2017-07-07 10:15:55
【问题描述】:

我有一个 HTML 文件在我的设备上可以正常显示,但它没有在我的设备上加载其中的 CSS 文件。当我在浏览器上打开 HTML 时,我的 CSS 工作正常。

这是我的 HTML 代码:

<head>
    <link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
    <h1>Prateek Bhatt</h1>
    <br>
    <p>is the greatest</p>
</body>

这是我的名为 stylesheet.css 的 CSS 文件:

body {
    background-color: lightblue;
}

h1 {
    color: navy;
    margin-left: 20px;
}

这也是 Swift 3 的代码:

class ViewController: UIViewController {

    @IBOutlet var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let htmlFile = Bundle.main.path(forResource: "index", ofType: "html")
        let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
        webView.loadHTMLString(html!, baseURL: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }    
}

【问题讨论】:

  • 我也是ios新手,所以不太了解。

标签: html ios css swift swift3


【解决方案1】:

按照这四个步骤在WebView 中加载CSS 文件:

第 1 步:Bundle 访问本地CSS 文件。
guard let path = Bundle.main.path(forResource: "Style", ofType: "css") else { return }

第 2 步: 获取String格式的CSS内容。
let cssString = try! String(contentsOfFile: path).trimmingCharacters(in: .whitespacesAndNewlines)

第 3 步: 将您的JavaScript 写在一个字符串中,以便稍后由WebView 评估。
let jsString = "var style = document.createElement('style'); style.innerHTML = '\(cssString)'; document.head.appendChild(style);"

第 4 步: 渲染 JavaScript。
webView.evaluateJavaScript(jsString, completionHandler: nil)

文档

【讨论】:

  • 我试过你写的但我得到了这个错误。我在这一行遇到错误- webView.evaluateJavaScript(jsString, completionHandler: nil) 错误是 - 'UIwebView' 类型的值没有成员 'evaluateJavaScript'
  • 请检查编辑部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 2013-04-09
  • 2012-06-25
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多