在SwiftUI中基于亮或暗模式更改buttonStyle修饰符 [英] Change buttonStyle Modifier based on light or dark mode in SwiftUI
本文介绍了在SwiftUI中基于亮或暗模式更改buttonStyle修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为明暗模式的按钮设置自定义buttonStyle
修饰符.
如何基于亮或暗模式更改buttonStyle修饰符?我想为按钮设置自定义"修改器,以实现明暗模式.
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.
这是我的按钮代码,
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)
}
}
)
}
}
对于深色模式,我还有另一种具有不同颜色和阴影的buttonStyle.
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)
但是有些我无法更改buttonStyle
修饰符.
But some how i'm not able to change buttonStyle
modifier.
推荐答案
只需将条件放在按钮样式修饰符之内,例如
Just put that condition inside button style modifier, like
// ... other your code
})
.buttonStyle(CustomButtonStyle(scheme: colorScheme)) // << here !!
并采用自定义样式
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
}
这篇关于在SwiftUI中基于亮或暗模式更改buttonStyle修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文