Created
August 16, 2023 14:28
-
-
Save allenhumphreys/4544187fae462fb1520bbf6d8505d8f5 to your computer and use it in GitHub Desktop.
SwiftUI Button Action Interposing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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