LoginSignup
4
5

More than 3 years have passed since last update.

[iOS13]アプリ内のLight <-> Dark切り替え

Last updated at Posted at 2019-11-05

UserInterfaceStyleをアプリで変更する方法をメモしておきます。

デモ

こんな感じのやつ
dark_and_light.gif

コード

import UIKit

final class ViewController: UIViewController {

    @IBOutlet private weak var userInterfaceStyleSwitch: UISwitch!
    @IBOutlet private weak var userInterfaceStatusLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        userInterfaceStyleSwitch.isOn = UITraitCollection.current.userInterfaceStyle == .dark
        userInterfaceStatusLabel.text = UITraitCollection.current.userInterfaceStyle == .dark ? "Dark" : "Light"
    }

    @IBAction private func switched(_ sender: UISwitch) {
        navigationController?.overrideUserInterfaceStyle = sender.isOn ? .dark : .light
        userInterfaceStatusLabel.text = sender.isOn ? "Dark" : "Light"
    }
}

解説

overrideUserInterfaceStyle はViewController単位で変更することが出来ます。
親のViewControllerが変更されたら子のViewControllerにも変更が適応されるので、今回は一番の親であるnavigationControllerのoverrideUserInterfaceStyleプロパティに変更を与えています。

4
5
0

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
4
5