Skip to content

Instantly share code, notes, and snippets.

@allenhumphreys
Created August 16, 2023 14:28
Show Gist options
  • Save allenhumphreys/4544187fae462fb1520bbf6d8505d8f5 to your computer and use it in GitHub Desktop.
Save allenhumphreys/4544187fae462fb1520bbf6d8505d8f5 to your computer and use it in GitHub Desktop.
SwiftUI Button Action Interposing
// Button styles are necessarily exclusive. If you return a Button from `makeBody`
// the next button style on the style stack
public struct TrackedButtonStyle: PrimitiveButtonStyle {
let action: () -> Void
public func makeBody(configuration: Configuration) -> some View {
Button {
action()
configuration.trigger()
} label: {
configuration.label
}
}
}
public extension PrimitiveButtonStyle where Self == TrackedButtonStyle {
static func track(_ action: @escaping () -> Void) -> TrackedButtonStyle { .init(action: action) }
}
Button("Button") {
print("Original action")
}
.buttonStyle(
.track {
print("My Special Action")
}
)
// Prints:
// My Special Action
// Original action
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment