我是 Swift UI 的新手,我为我的公司创建了一个应用程序,我创建了一个 webView 来在应用程序主页上显示一些新闻,我从我们的网站获取它,但我想隐藏一些菜单和其他东西来制作它更干净,但我什至不知道如何启动它,我的应用程序可以显示“原始”网页,如果你们能帮助我那就太棒了
这是我的代码
import SwiftUI
import WebKit
struct Home: View {
@State private var showWebView = false
private let urlString: String = "https://mywebsite"
@Binding var showMenu: Bool
var body: some View {
VStack{
HStack{
WebViewHome(url: URL(string: urlString)!).frame(height: .infinity)
}
.padding([.top],0)
Spacer()
}
}
}
struct WebViewHome: UIViewRepresentable{
var url: URL
func makeUIView(context: Context) -> WKWebView {
let prefs = WKWebpagePreferences()
prefs.allowsContentJavaScript = true
let config = WKWebViewConfiguration()
config.defaultWebpagePreferences = prefs
return WKWebView()
}
func updateUIView(_ uiView: WKWebView, context: Context) {
let request = URLRequest(url: url)
uiView.load(request)
}
}
将 JavaScript 注入网页来操作 DOM。 您需要知道要隐藏的元素的 CSS 选择器:
struct WebViewHome: UIViewRepresentable {
var url: URL
var js: String = """
document.querySelector('selector').style.display='none';
document.querySelector('another-selector').style.display='none';
// Add more selectors
"""
func makeUIView(context: Context) -> WKWebView {
let prefs = WKWebpagePreferences()
prefs.allowsContentJavaScript = true
let config = WKWebViewConfiguration()
config.defaultWebpagePreferences = prefs
let webView = WKWebView(frame: .zero, configuration: config)
webView.navigationDelegate = context.coordinator
return webView
}
func updateUIView(_ uiView: WKWebView, context: Context) {
let request = URLRequest(url: url)
uiView.load(request)
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, WKNavigationDelegate {
var parent: WebViewHome
init(_ parent: WebViewHome) {
self.parent = parent
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript(parent.js, completionHandler: nil)
}
}
}