如何检查设备上的暗模式是否已启用。我想从视图中检查它并有条件地显示或隐藏阴影。
我以为我可以从环境中获取 colorScheme 但我想我错过了一些东西。
struct FloatingAddButton : View {
@Environment(\.colorScheme) var colorScheme
@Binding var openAddModal: Bool
var body : some View {
VStack {
Spacer()
HStack() {
Spacer()
Button(action: {
self.openAddModal = true
}) {
ZStack {
Circle()
.foregroundColor(Color(RetroTheme.shared.appMainTint))
.frame(width: 50, height: 50, alignment: .center)
if(self.colorScheme == .light) {
.shadow(color: .secondary, radius: 5, x: 0, y: 0)
}
Image(systemName: "plus")
.foregroundColor(Color.white)
}
} // End Button
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的代码中,我有一个简单的 View 扩展,这使代码更具可读性。有了它,我可以有条件地应用修饰符:
.conditionalModifier(self.colorScheme == .light, LightShadow())
Run Code Online (Sandbox Code Playgroud)
完整的实现如下:
extension View {
// If condition is met, apply modifier, otherwise, leave the view untouched
public func conditionalModifier<T>(_ condition: Bool, _ modifier: T) -> some View where T: ViewModifier {
Group {
if condition {
self.modifier(modifier)
} else {
self
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
struct FloatingAddButton : View {
@Environment(\.colorScheme) var colorScheme
@Binding var openAddModal: Bool
var body : some View {
VStack {
Spacer()
HStack() {
Spacer()
Button(action: { self.openAddModal = true }) {
ZStack {
Circle()
.foregroundColor(Color(.red))
.frame(width: 50, height: 50, alignment: .center)
.conditionalModifier(self.colorScheme == .light, LightShadow())
Image(systemName: "plus")
.foregroundColor(Color.white)
}
}
} // End Button
}
}
}
struct LightShadow: ViewModifier {
func body(content: Content) -> some View {
content.shadow(color: .secondary, radius: 5, x: 0, y: 0)
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想为 true 和 false 应用不同的修饰符,这是另一个扩展:
extension View {
// Apply trueModifier if condition is met, or falseModifier if not.
public func conditionalModifier<M1, M2>(_ condition: Bool, _ trueModifier: M1, _ falseModifier: M2) -> some View where M1: ViewModifier, M2: ViewModifier {
Group {
if condition {
self.modifier(trueModifier)
} else {
self.modifier(falseModifier)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1464 次 |
| 最近记录: |