You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 5中动态URL场景下WKWebView无法适配系统明暗模式问题求助

适配方案

1. 实现逻辑

无需依赖固定加载URL,通过WKWebView全局注入自动执行的JS脚本,在所有页面DOM加载完成后插入暗黑模式适配样式,结合系统明暗模式查询规则自动调整页面显示,同时对媒体资源做特殊处理避免反色异常。

2. 完整修改代码

class DownloadViewController: UIViewController {
    
    @IBOutlet weak var webView: WKWebView!
    // 全局暗黑模式适配脚本,所有加载页面自动生效
    private let darkModeScript = """
    (function() {
        // 避免重复注入样式
        if (document.getElementById('darkModeAdaptStyle')) return;
        const style = document.createElement('style');
        style.id = 'darkModeAdaptStyle';
        style.textContent = `
            @media (prefers-color-scheme: dark) {
                html {
                    filter: invert(1) hue-rotate(180deg);
                    background: #fff !important;
                }
                /* 媒体资源二次反转恢复正常显示 */
                img, video, iframe, canvas, svg, [style*="background-image"] {
                    filter: invert(1) hue-rotate(180deg);
                }
            }
        `;
        document.head.appendChild(style);
    })();
    """

    override func viewDidLoad() {
        super.viewDidLoad()
        // 基础样式配置,避免加载过程白屏
        webView.overrideUserInterfaceStyle = .unspecified
        webView.isOpaque = false
        webView.backgroundColor = .systemBackground
        
        // 注册全局注入脚本,所有页面加载完成后自动执行
        let userScript = WKUserScript(source: darkModeScript, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
        webView.configuration.userContentController.addUserScript(userScript)
        
        webView.uiDelegate = self
        webView.navigationDelegate = self
        webView.load(URLRequest(url: URL(string: "https://www.google.com")!))
        webView.allowsBackForwardNavigationGestures = true
        webView.allowsLinkPreview = true
    }
    
    // 监听系统明暗模式切换,实时刷新页面样式
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        guard traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) else { return }
        webView.evaluateJavaScript(darkModeScript)
    }
}

3. 可选优化

如果遇到部分本身已适配暗黑模式的站点样式冲突,可以在脚本中添加对应站点域名判断逻辑,跳过重复适配即可。

内容的提问来源于stack exchange,提问作者Yogesh Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 13:30:00