Swift:如何使用 WKWebView 使用 # 标签导航到 HTML 书签?
Swift: How do I navigate to an HTML bookmark using # tags using WKWebView?
我正在尝试使用 WKWebView 加载 HTML 文件,但我希望我的应用程序转到网页中的特定点。 HTML 本身包含 <a name="bookmark7">
标签。如果我要使用浏览器,我会直接在文件名后使用 # 附加 link 名称,如下所示:http://mywebsite.com/index.html#bookmark1
我试过以下方法都没有用:
let bookmark = "#bookmark1"
let url = Bundle.main.url(forResource: "index", withExtension: "html\(bookmark)", subdirectory: "website")!
uiView.loadFileURL(url, allowingReadAccessTo: url)
这给了我一个预览错误,无法加载。如何跳转到 HTML 页面中的特定点?任何方法都行。完整的 SwiftUI 视图如下:
import SwiftUI
import WebKit
struct CodeView: View {
var body: some View {
WebView()
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
}
}
struct WebView: UIViewRepresentable {
func makeUIView(context: Context) -> WKWebView {
return WKWebView()
}
func updateUIView(_ uiView: WKWebView, context: Context) {
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "website")!
uiView.loadFileURL(url, allowingReadAccessTo: url)
}
}
struct CodeView_Previews: PreviewProvider {
static var previews: some View {
CodeView()
}
}
这是工作变体(使用 Xcode 12 / iOS 14 测试)
func updateUIView(_ uiView: WKWebView, context: Context) {
guard let resourceURL = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "website") else { return }
let path = resourceURL.absoluteString + "#bookmark1"
if let url = URL(string: path) {
uiView.loadFileURL(url, allowingReadAccessTo: url)
}
}
我正在尝试使用 WKWebView 加载 HTML 文件,但我希望我的应用程序转到网页中的特定点。 HTML 本身包含 <a name="bookmark7">
标签。如果我要使用浏览器,我会直接在文件名后使用 # 附加 link 名称,如下所示:http://mywebsite.com/index.html#bookmark1
我试过以下方法都没有用:
let bookmark = "#bookmark1"
let url = Bundle.main.url(forResource: "index", withExtension: "html\(bookmark)", subdirectory: "website")!
uiView.loadFileURL(url, allowingReadAccessTo: url)
这给了我一个预览错误,无法加载。如何跳转到 HTML 页面中的特定点?任何方法都行。完整的 SwiftUI 视图如下:
import SwiftUI
import WebKit
struct CodeView: View {
var body: some View {
WebView()
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
}
}
struct WebView: UIViewRepresentable {
func makeUIView(context: Context) -> WKWebView {
return WKWebView()
}
func updateUIView(_ uiView: WKWebView, context: Context) {
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "website")!
uiView.loadFileURL(url, allowingReadAccessTo: url)
}
}
struct CodeView_Previews: PreviewProvider {
static var previews: some View {
CodeView()
}
}
这是工作变体(使用 Xcode 12 / iOS 14 测试)
func updateUIView(_ uiView: WKWebView, context: Context) {
guard let resourceURL = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "website") else { return }
let path = resourceURL.absoluteString + "#bookmark1"
if let url = URL(string: path) {
uiView.loadFileURL(url, allowingReadAccessTo: url)
}
}