티스토리 뷰

🍏/iOS

[CSS] WKWebview DarkMode 대응

eungding 2020. 12. 8. 20:53
728x90
반응형

Supporting Dark Mode in Your Web Content WWDC 영상을 보고 테스트해본 기록 ✏️

 

웹뷰를 다크모드 대응해주기 위해 

CSS쪽에서 간단한 대응을 해주면 됩니다..! 

 

[ 준비 ]

 

아래와 같이 테스트할 준비를 해주세요

저 URL이 내려주는 CSS를 바꿔가면서 테스트 해볼게요

 

import UIKit
import WebKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupWebView()
}
private func setupWebView() {
let webView = WKWebView(frame: view.bounds)
view.addSubview(webView)
webView.load(URLRequest(url: URL(string: "https://eunjin3786.github.io/darkmode-test.html")!))
}
}

 

[ 기본 CSS ] 

 

이렇게 생긴 CSS가 있다고 해보겠습니다. 

참고로 <style> </style> 태그 안에 css코드를 넣는 것보다 

 

stylesheet.css 파일을 따로 만들고 

아래와 같이 css를 넣어주는게 더 좋은 방법이에요!+! 

 

<head>

<link rel="stylesheet" href="stylesheet.css">

</head>

 

 

저는 테스트니까 이렇게 할게요 

 

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Dark Mode</title>
<style>
h1 {
font-size: 1000%;
}
h2 {
font-size: 500%;
}
</style>
</head>
<body>
<h1> 안녕하세요 </h1>
<h2> 다크모드 테스트 입니다 😜 </h2>
</body>
</html>
view raw css-default.css hosted with ❤ by GitHub

 

테스트해보면 다크모드 반영이 안됩니다. 

 

 

 

[ 다크모드 대응 CSS ]

 

애플에서 추가해주라는 것을 추가해볼게요

이것을 CSS에 추가하면 다크/라이트 모드를 구분할 수 있고 기본 반전 컬러가 적용됩니다. 

 

 

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Dark Mode</title>
<style>
:root {
color-scheme: light dark;
}
h1 {
font-size: 1000%;
}
h2 {
font-size: 500%;
}
</style>
</head>
<body>
<h1> 안녕하세요 </h1>
<h2> 다크모드 테스트 입니다 😜 </h2>
</body>
</html>

 

다크모드 반영이 잘됩니다.

 

 

 

이번에는 기본 반전 컬러말고 

원하는 컬러를 지정해볼게요=! 

라이트모드일때는 빨간색, 

다크모드일때는 초록색으로 나오게 해볼게요

 

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Dark Mode</title>
<style>
/* 라이트모드 컬러 셋 */
:root {
color-scheme: light dark;
--h1-color: red;
--h2-color: red;
}
/* 다크모드 컬러 셋 */
@media screen and (prefers-color-scheme: dark) {
:root {
--h1-color: green;
--h2-color: green;
}
}
h1 {
font-size: 1000%;
color: var(--h1-color);
}
h2 {
font-size: 500%;
color: var(--h2-color);
}
</style>
</head>
<body>
<h1> 안녕하세요 </h1>
<h2> 다크모드 테스트 입니다 😜 </h2>
</body>
</html>

 

이것도 잘됩니다! 

 

 

 

 

[ Reference ]

 

github.com/kharrison/CodeExamples/tree/main/DynamicWebKit/DynamicWebKit

 

kharrison/CodeExamples

Code Examples. Contribute to kharrison/CodeExamples development by creating an account on GitHub.

github.com

 

반응형
댓글