SwiftUI项目判断是否为暗黑模式

实现

1
2
3
4
5
@Environment(\.colorScheme) var colorScheme

var isLight: Bool {
  colorScheme == .light
}

调用

1
2
Text("Hello, World !")
	.foregroundColor(isLight ? Color.red : Color.green)

完整例子

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import SwiftUI

struct CheckIsLight: View {
    
    @Environment(\.colorScheme) var colorScheme

    var isLight: Bool {
      colorScheme == .light
    }
    
    var body: some View {
        Text("Hello, World !")
            .foregroundColor(isLight ? Color.red : Color.green) // 此处使用isLght实现根据暗黑模式切换字体颜色
    }
}

struct CheckIsLight_Previews: PreviewProvider {
    static var previews: some View {
        CheckIsLight()
    }
}
Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy