2024-12-19
手机下的小按钮 - ColorScheme
写两个Preview代码即可
#Preview {
DarkModeBootCamp()
.preferredColorScheme(.dark)
}
#Preview {
DarkModeBootCamp()
.preferredColorScheme(.light)
}
.primary
默认情况下,在白色背景下是黑色,在黑色背景下是白色
.secondary
一直是灰色
Assets - 右键添加ColorSet - 打开inspectors窗口 - 选择白天暗夜的颜色
颜色会全局自适应。
@Environment(\.colorScheme) private var colorScheme
Text("This color is locally adaptive!")
.foregroundStyle(colorScheme == .light ? .green : .yellow)
import SwiftUI
struct DarkModeBootCamp: View {
@Environment(\.colorScheme) private var colorScheme
var body: some View {
NavigationView{
ScrollView{
VStack(spacing:20){
Text("This text is PRIMARY")
.foregroundStyle(.primary)
Text("This text is SECONDARY")
.foregroundStyle(.secondary)
Text("This text is BLACK")
.foregroundStyle(.black)
Text("This text is WHITE")
.foregroundStyle(.white)
Text("This color is globally adaptive!")
.foregroundStyle(.adaptive)
Text("This color is locally adaptive!")
.foregroundStyle(colorScheme == .light ? .green : .yellow)
}
}
.navigationTitle("Dark Mode Bootcamp")
}
}
}
#Preview {
DarkModeBootCamp()
.preferredColorScheme(.dark)
}
#Preview {
DarkModeBootCamp()
.preferredColorScheme(.light)
}