问题
I want to set Custom buttonStyle
modifier for button for light and dark mode.
How to change buttonStyle Modifier based on light or dark mode? I want to set Custom modifier for my button for light and dark mode.
here is my button code,
Button(action: {
print("button tapped")
}, label: {
LinearGradient(gradient: Gradient(colors: [.darkBlueColor, .lightBlueColor]), startPoint: .top, endPoint: .bottom)
.mask(Image(systemName: "ellipsis")
.resizable()
.aspectRatio(contentMode: .fit)
).frame(width: iPhoneSE ? 26 : 25, height: iPhoneSE ? 26 : 25, alignment: .center)
})
.buttonStyle(lightButtonStyle())
struct lightButtonStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.padding(10)
.background(
Group {
if configuration.isPressed {
Circle()
.fill(Color.offWhite)
.overlay(
Circle()
.stroke(Color.lightGray2, lineWidth: 4)
.blur(radius: 1)
.offset(x: 2, y: 2)
.mask(Circle().fill(LinearGradient(Color.black, Color.clear)))
)
.overlay(
Circle()
.stroke(Color.white, lineWidth: 4)
.blur(radius: 1)
.offset(x: -2, y: -2)
.mask(Circle().fill(LinearGradient(Color.clear, Color.black)))
)
} else {
Circle()
.fill(Color.offWhite)
.shadow(color: Color.white.opacity(0.8), radius: 1, x: -2, y: -2)
.shadow(color: Color.lightPurple.opacity(0.6), radius: 1, x: 2, y: 2)
}
}
)
}
}
For Dark mode i've another buttonStyle with different color and shadows.
i know we can change other modifiers like this,
.fill(colorScheme == .dark ? Color.darkEnd : Color.white)
But some how i'm not able to change buttonStyle
modifier.
回答1:
Just put that condition inside button style modifier, like
// ... other your code
})
.buttonStyle(CustomButtonStyle(scheme: colorScheme)) // << here !!
and in custom style
struct CustomButtonStyle: ButtonStyle {
var scheme: ColorScheme // << here !!
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.padding(10)
Group {
if configuration.isPressed {
Circle() // example of internal dependency on scheme
.fill(self.scheme == .dark ? Color.offBlack : Color.offWhite)
// .. other code here
}
回答2:
You could define a named color in Assets.xcassets with a variation for the dark mode:
This works out of the box even in a ButtonStyle:
Color("ButtonBorder")
来源:https://stackoverflow.com/questions/61943846/change-buttonstyle-modifier-based-on-light-or-dark-mode-in-swiftui