Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ryo-takahashi/99344509c0720e5ed040da4b9fcd8c60 to your computer and use it in GitHub Desktop.
Save ryo-takahashi/99344509c0720e5ed040da4b9fcd8c60 to your computer and use it in GitHub Desktop.
iOS アプリ内からカラーテーマを変更する
if #available(iOS 13.0, *) {
switch type {
case .light:
UIApplication.shared.keyWindow?.overrideUserInterfaceStyle = .light
case .dark:
UIApplication.shared.keyWindow?.overrideUserInterfaceStyle = .dark
case .conformedSystem:
UIApplication.shared.keyWindow?.overrideUserInterfaceStyle = UITraitCollection.current.userInterfaceStyle
case .unknown: break
}
}
@ryo-takahashi
Copy link
Author

  • conformedSystem はシステムに準拠する設定
  • type の値はアプリ内で永続化保存している
  • ↑のデータが更新されたときにここを呼び出す。 そのときの type の値は更新後のモノ
  • conformedSystem の状態でOS側のテーマを変更したとき、いい感じに更新はしてくれないのでOS側のテーマ変更時に別途ここを呼び出す制御を入れておく必要がある。

@ryo-takahashi
Copy link
Author

ryo-takahashi commented Mar 24, 2020

一部切り替わらないヤツらがいるときは、以下のような制御を入れる

        if #available(iOS 13.0, *) {
            let titleColor = R.color.black()?.resolvedColor(with: UITraitCollection(userInterfaceStyle: AppearanceManager.shared.currentAppearanceType.userInterfaceStyle))
            segmentedControl.titleTextAttributes = [NSAttributedString.Key.foregroundColor: titleColor ?? UIColor.black, NSAttributedString.Key.font: font]
        } else {
            segmentedControl.titleTextAttributes = [NSAttributedString.Key.foregroundColor: R.color.black() ?? UIColor.black, NSAttributedString.Key.font: font]
        }

他にも、UITraitCollectionによるUIColorのresolveは以下の方法がある。

let layer = CALayer()
let traitCollection = view.traitCollection

// #1
traitCollection.performAsCurrent {
layer.borderColor = UIColor.label.cgColor
}

// #2
UITraitCollection.current = traitCollection
layer.borderColor = UIColor.label.cgColor

@ryo-takahashi
Copy link
Author

ryo-takahashi commented Mar 24, 2020

type の型は以下である

    enum MyAppearanceType: String {
        case unknown
        case light
        case dark
        case conformedSystem
            
        @available(iOS 13.0, *)
        var userInterfaceStyle: UIUserInterfaceStyle {
            switch self {
            case .light:
                return .light
            case .dark:
                return .dark
            case .conformedSystem:
                return UITraitCollection.current.userInterfaceStyle
            case .unknown:
                return .unspecified
            }
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment