how to use iOS 13 darkmode for wkwebview

Vinu David Jose picture Vinu David Jose · Jul 25, 2019 · Viewed 8.9k times · Source

I was working for iOS 13 with Xcode 11 beta. Is there any way to support dark mode on web views? I have created a color set for all the other views except WKWebviews. How to change web view background and text color for dark mode?

Answer

rmaddy picture rmaddy · Jul 25, 2019

Assuming your question is asking how to change the colors of the HTML content you are displaying in a WKWebView based on whether light or dark mode is in effect, there is nothing you do in your app's code. All changes need to be in the CSS being used by your HTML content.

I have some local HTML files I use in a WKWebView. I was able to support dark mode by updating my css file.

Let's say you currently have a css file with the following:

body {
    background-color: white;
    color: black;
}

a:link {
    color: #0078b5;
    text-decoration: none;
}

Those are fine in light mode. To also support dark mode, you can add an @media section to your css:

@media (prefers-color-scheme: dark) {
    body {
        background-color: rgb(38,38,41);
        color: white;
    }
    a:link {
        color: #0096e2;
    }
    a:visited {
        color: #9d57df;
    }
}

When in dark mode, the colors in this @media section will override the corresponding colors defined outside the @media section.