gpt4 book ai didi

html - 如何在 Swift 3 中加载带有 HTML 的 CSS 文件?

转载 作者:搜寻专家 更新时间:2023-10-31 22:41:50 24 4
gpt4 key购买 nike

我有一个 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.
}
}

最佳答案

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

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

第 2 步:获取 String 格式的 CSS 内容。
让 cssString = 尝试!字符串(contentsOfFile:路径).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)

DOCUMENTATION

关于html - 如何在 Swift 3 中加载带有 HTML 的 CSS 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44968287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com