我在使用Xcode 11 beta的iOS 13上工作。有什么方法可以在Web视图上支持暗模式吗?我为WKWebviews以外的所有其他视图创建了颜色集。如何在黑暗模式下更改Web视图的背景和文本颜色?
答案 0 :(得分:4)
在迁移iOS应用程序时,我遇到了同样的挑战,因为我们确实使用WKWebView
登录,而在我咨询时,发现以下示例可以处理这种情况。只需为颜色创建变量,并在CSS中进行处理即可。
之前
body { color: black; }
h1 { color: white; }
.header {
background-color: #FFFFFF;
color: white;
}
之后
:root {
color-scheme: light dark;
--h1-color: #333;
--header-bg-clr: #FFF1FF;
--header-txt-clr: white;
}
@media (prefers-color-scheme: dark) {
:root {
color-scheme: light dark;
--h1-color: #333;
--header-bg-clr: #FFF1FF;
--header-txt-clr: white;
}
}
body { }
h1 { color: var(--h1-color); }
.header {
background-color: var (--header-bg-clr);
color: var(--header-txt-clr);
}
在集成了此更改之后,您可以使用Safari进行测试(首先需要在Sarafi,Preferences和Advanced中启用开发人员菜单选项)。打开wen inspector(使用Command + Option + I),您将看到此屏幕,其中包含用于切换亮/暗模式的选项。
注意,仅添加更多信息。您还可以像处理颜色一样处理不同的图像。
之前
<img src="day.jpg">
之后
<picture>
<source srcset="light.jpg" media="(prefers-color-scheme: light)">
<img src="day.jpg">
</picture>
答案 1 :(得分:2)
更简单,只需反转图像以外的所有颜色和样式:
@media (prefers-color-scheme: dark) {
html{
filter: invert(1) hue-rotate(.5turn);
}
img {
filter: invert(1) hue-rotate(.5turn);
}
}
答案 2 :(得分:2)
快捷键5
对于WKWebView
,下面的代码对我有用。
extension RichTextController : WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
let cssString = "@media (prefers-color-scheme: dark) {body {color: white;}a:link {color: #0096e2;}a:visited {color: #9d57df;}}"
let jsString = "var style = document.createElement('style'); style.innerHTML = '\(cssString)'; document.head.appendChild(style);"
webView.evaluateJavaScript(jsString, completionHandler: nil)
}
}
答案 3 :(得分:1)
假设您的问题是询问是否根据亮还是暗模式来更改WKWebView中显示的HTML内容的颜色,那么您在应用程序的代码中无需执行任何操作。所有更改都必须在HTML内容所使用的CSS中。
我在WKWebView中使用了一些本地HTML文件。通过更新CSS文件,我能够支持暗模式。
假设您当前有一个css文件,其中包含以下内容:
body {
background-color: white;
color: black;
}
a:link {
color: #0078b5;
text-decoration: none;
}
在光照模式下可以使用。为了也支持暗模式,可以在CSS中添加一个@media
部分:
@media (prefers-color-scheme: dark) {
body {
background-color: rgb(38,38,41);
color: white;
}
a:link {
color: #0096e2;
}
a:visited {
color: #9d57df;
}
}
在黑暗模式下,此@media
部分中的颜色将覆盖@media
部分之外定义的相应颜色。
答案 4 :(得分:0)
根标签将反转所有成分的颜色,但表格和图像将为负数。
要执行完美的颜色反转,请检查以下CSS文件
@media (prefers-color-scheme: dark) {
/* root tag inverting all the components color except the table.*/
: root {
color-scheme: light dark;
filter: invert(100%);
-webkit-filter: invert(100%)
}
/*table tag needed for inverting table content.*/
table {
filter: invert(100%);
}
/* If We do color invert in : root , images will be color inverted and it will be in negative. If we invert again these negative images, it will be positive.*/
img {
filter: invert(100%);
}
}