I'm attempting to recreate a button that simulates the behavior of a NavigationLink inside a List in SwiftUI. However, when tapping the button wrapped inside the List, the listRowBackground color doesn't change, even when long-pressing due to my Custom ButtonStyle. When removing the ButtonStyle, the ListRowBackground stays the same on short tap. However, on long press it now changes the color. I just want the Button to change the ListRowBackgroundColor on short- and longpress.
Here's a simplified version of my code:
List {
NavigationButton(imageString: "lock.fill", imageColor: .cyan, text: "Data Protection") {
// Action
}
}
private struct NavigationButton: View {
@Environment(\.colorScheme) var colorScheme
let imageString: String
let imageColor: Color
let text: String
let action: () -> Void
var body: some View {
Button {
action()
} label: {
// Button content
}
.buttonStyle(NavigationLinkButtonStyle())
}
}
private struct NavigationLinkButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.listRowBackground(configuration.isPressed ? Color.red.opacity(0.3) : Color.red)
}
}
In this code, the default background color of the ListRowBackground is set to red for testing purposes. However, the background remains the default SwiftUI List color when the button is tapped.
I have also tried setting the ListRowBackground directly after the NavigationButton:
List {
NavigationButton(imageString: "lock.fill", imageColor: .cyan, text: "Data Protection") {
// Action
}
.listRowBackground(Color.red)
}
This resulted in the view actually having the Backgroundcolor, but now I'd need to pass a Binding down to the ButtonStyle and change it down there, when configuration.isPressed changes to adjust the ListRowBackground in the view, which is really suboptimal.
How can I fix this and adjust the background color correctly, as it is in the default NavigationLink?