Devlog: Nov 17, 2022
Just been working on some small polish things. Like real small things—make sure the buttons have the right color. So I over-engineered it! I always forget how to make custom ButtonStyle
, so putting this here for reference. I have a view modifier for the shared stuff between multiple button styles that can simply be used like .buttonBase
. Than to style a button, .buttonStyle(.primaryButton)
. Easy! Definitely worth the effort for the 2 buttons I have. But did do some Swift generics stuff which is always exciting…
struct ButtonBase<S: ShapeStyle>: ViewModifier {
let background: S
let isPressed: Bool
func body(content: Content) -> some View {
content
.padding(.horizontal, 20)
.padding(.vertical, 6)
.background(background)
.opacity(isPressed ? 0.5 : 1)
}
}
extension View {
func buttonBase<S: ShapeStyle>(background: S, isPressed: Bool) -> some View {
modifier(ButtonBase(background: background, isPressed: isPressed))
}
}
struct PrimaryButton: ButtonStyle {
@Environment(\.colorScheme) private var colorScheme
func makeBody(configuration: Configuration) -> some View {
configuration.label
.buttonBase(background: Color.primary, isPressed: configuration.isPressed)
}
}
extension ButtonStyle where Self == PrimaryButton {
static var primary: Self {
return .init()
}
}