In my project, I am using my custom shape as a button’s label. Now, I am trying to create a custom ButtonStyle
which changes the custom shape’s color whenever a button is currently pressed.
If I were to use a "normal" Button label, e.g. a Text
, I could do this:
struct LightGrayButtonStyle: ButtonStyle {
func makeBody(configuration: Self.Configuration) -> some View {
configuration.label
.foregroundColor(configuration.isPressed ? .black : .red)
}
}
However, configuration.label
does not have any Shape
specific view modifiers, making it impossible to alter the color using .fill
for example.
This is the rest of my code:
Button {
action()
} label: {
RingSegment() // this is my custom shape
}
.buttonStyle(LightGrayButtonStyle()) // I apply my custom button style
How can I now change the color of my custom shape inside my custom ButtonStyle
? Alternatively, how can I make my custom shape respect the provided foregroundColor
which I can set inside the makeBody
method implemented by my LightGrayButtonStyle
?
2
Answers
The solution I went for is to apply the
foregroundColor
modifier inside themakeBody
function and use that color when filling my custom shape.This is my code:
You can move all the code inside the
ButtonStyle
Then you can pass in any
Shape
and anyColor
.