import SwiftUI import SafariServices // MARK: - Web View Component struct WebView: UIViewControllerRepresentable { let url: URL func makeUIViewController(context: Context) -> SFSafariViewController { let config = SFSafariViewController.Configuration() config.entersReaderIfAvailable = false config.barCollapsingEnabled = true let safariViewController = SFSafariViewController(url: url, configuration: config) safariViewController.preferredBarTintColor = UIColor.systemBackground safariViewController.preferredControlTintColor = UIColor.systemBlue return safariViewController } func updateUIViewController(_ uiViewController: SFSafariViewController, context: Context) { // Safari View Controller 不需要更新 } } // MARK: - Web View Modifier extension View { /// 显示 Web 页面的修饰符 /// - Parameters: /// - isPresented: 是否显示的绑定变量 /// - url: 要显示的 URL /// - Returns: 修饰后的视图 func webView(isPresented: Binding, url: URL?) -> some View { self.sheet(isPresented: isPresented) { if let url = url { WebView(url: url) } else { Text("无法加载页面") .foregroundColor(.red) .padding() } } } } #Preview { VStack { Button("打开网页") { // 预览时不执行任何操作 } } .webView( isPresented: .constant(true), url: URL(string: "https://www.apple.com") ) }