I have a standard ButtonStyle that I use for all the buttons in my app:
import SwiftUI
public struct DefaultButtonStyle: ButtonStyle
{
let color: Color
init() { color = colorDefaultButton }
init(color: Color) { self.color = color }
public func makeBody(configuration: Self.Configuration) -> some View
{
configuration.label
.frame(width: 90.0, height: 25.0)
.background(color)
.foregroundColor(.white)
.cornerRadius(8.0)
.overlay(RoundedRectangle(cornerRadius: 5.0)
.stroke(lineWidth: 1))
.scaleEffect(configuration.isPressed ? 0.9 : 1)
.shadow(color: .gray,
radius: configuration.isPressed ? 4 : 6,
x: configuration.isPressed ? 4 : 6,
y: configuration.isPressed ? 4 : 6)
}
}
I would like to execute code every time I define the button. For illustration, here is the code attached to a single button:
Button("Export")
{
showingExporter = true
document.message = periodicals.getDataAsString() ?? "No Data"
let generator = UIImpactFeedbackGenerator(style: .soft)
generator.impactOccurred()
}
.padding([.leading, .bottom])
.buttonStyle(DefaultButtonStyle())
.fileExporter(isPresented: $showingExporter,
document: document,
contentType: .plainText)
I want to have the two lines creating and activating the feedback generator executed for every button, but I’m hoping to invoke it from the ButtonStyle so I don’t have to code it for each button.
Is there a way to do this?