LoginSignup
11
6

More than 1 year has passed since last update.

【Swift】アプリ内でダークモード/ライトモードを設定したい

Posted at

やりたいこと

アプリ内で、OS設定によらずライトモード/ダークモードを設定したい。

設定方法

1行加えるだけで、即時にアプリ全体に反映されます。

  • ダークモードに設定する場合
ViewController.swift
UIApplication.shared.windows.first?.overrideUserInterfaceStyle = .dark
  • ライトモードに設定する場合
ViewController.swift
UIApplication.shared.windows.first?.overrideUserInterfaceStyle = .light
  • OS設定に従う場合
ViewController.swift
UIApplication.shared.windows.first?.overrideUserInterfaceStyle = .unspecified

起動時に設定する場合は、initial view controllerの viewDidLoad() 内に書くと良いでしょう。
なお、AppDelegate内の application(_:didFinishLaunchingWithOptions:) 内に記載しても、うまく動作しません。(詳しく調べてはいませんが、おそらく、UIWindowオブジェクトがまだ構成されていないからではないかと思います。)

動作確認環境

Xcode: 12.5
iOS: 14.7.1
Swiftバージョン: Swift 5.4

以上

11
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
6