1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【SwiftUI】現在のテーマが通常かダークテーマか調べる

Last updated at Posted at 2019-12-31

概要

現在のテーマが、端末で設定されているダークテーマかライトテーマ(通常)か調べる方法

方法

現在設定されているテーマを、


@Environment(\.colorScheme) var colorScheme: ColorScheme

を使って取得します

ColorScheme は、 ColorScheme.darkColorScheme.light というプロパティが存在しており、取得したcolorSchemeには上記のどちらかが設定されています

実装例

下記の例では現在のテーマを取得して、それに合わせた文字の色を設定しています

struct ContentView: View {

    //1. 現在の設定を取得
    @Environment(\.colorScheme) var colorScheme: ColorScheme

    var body: some View {
       Text("Hello World!")
           //2. 定義した変数のcolorSchemeを使って調べる(ダークテーマの場合は ColorScheme.dark)
           .foregroundColor(colorScheme == ColorScheme.light ? .black : .white)
    }


    struct ContentView_Previews : PreviewProvider {
        static var previews: some View {
            Group {
         //ライトテーマ(通常)
                ContentView()
         //ダークテーマ
                ContentView().environment(\.colorScheme, .dark)
            }
        }
    }

}

参考文献

Xcode 11 -- SwiftUI's dark mode setup - Stack Overflow

[ColorScheme - SwiftUI | Apple Developer Documentation] (https://developer.apple.com/documentation/swiftui/colorscheme)

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?