gpt4 book ai didi

ios - SWIFT - 加载本地 CSS 文件

转载 作者:搜寻专家 更新时间:2023-11-01 07:11:50 24 4
gpt4 key购买 nike

我正在尝试向我的 webview 添加一些本地 css,但我的应用程序中的 css 文件似乎有问题:

enter image description here

当我尝试从本地 css 文件加载 css 时没有任何反应,但是当我用在线 css 文件替换“%@”时它工作正常。

感谢您的帮助。

import UIKit

class ViewController: UIViewController, UIWebViewDelegate {

@IBOutlet weak var webview: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
webview.delegate = self

let html: String! = "<html><head></head><body><div id=\"postcontent\"><h1>Hello</h1></div></body></html>"

webview.loadHTMLString(html, baseURL: nil)
}

func webViewDidFinishLoad(_ webView: UIWebView){
let path = Bundle.main.path(forResource: "styles", ofType: "css")

let javaScriptStr: NSString = "var link = document.createElement('link'); link.href = '%@'; link.rel = 'stylesheet'; document.head.appendChild(link)"
let javaScripthPath = NSString(format: javaScriptStr, path!)
webview.stringByEvaluatingJavaScript(from: javaScripthPath as String)
print(javaScripthPath)
}
}

最佳答案

您的 HTML 文件是从字符串加载的,因此它被加载到无法访问文件系统上的文件的 Web View 中(可能是由于浏览器实现的同源策略)。它只能访问类似通过loadHTMLString 注入(inject)的资源。

如果您想使用本地 CSS,请从文件而不是字符串加载 HTML。如果它在同一目录中,这将使 Web View 访问 CSS。

这是一个演示,首先,HTML 现在是一个文件。

enter image description here

然后,您的代码可能如下所示:

class ViewController: UIViewController, UIWebViewDelegate {

@IBOutlet weak var webview: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
webview.delegate = self

let path = Bundle.main.path(forResource: "app", ofType: "html")!
let url = URL(fileURLWithPath: path)
let request = URLRequest(url: url)

webview.loadRequest(request)
}

func webViewDidFinishLoad(_ webView: UIWebView){
let path = Bundle.main.path(forResource: "styles", ofType: "css")!

let javaScriptStr = "var link = document.createElement('link'); link.href = '\(path)'; link.rel = 'stylesheet'; document.head.appendChild(link)"
webview.stringByEvaluatingJavaScript(from: javaScriptStr)
}
}

关于ios - SWIFT - 加载本地 CSS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44476826/

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