Skip to content

Instantly share code, notes, and snippets.

@franckclement
Created November 27, 2019 20:41
Show Gist options
  • Save franckclement/f19412c91e88af05e7c57f15fa169962 to your computer and use it in GitHub Desktop.
Save franckclement/f19412c91e88af05e7c57f15fa169962 to your computer and use it in GitHub Desktop.
import SwiftUI
struct FeedbackPreparationButtonStyle: ButtonStyle {
let feedbackGenerator: UIImpactFeedbackGenerator
func makeBody(configuration: Configuration) -> some View {
if configuration.isPressed { feedbackGenerator.prepare() }
return configuration.label
// Mimic the default ButtonStyle which we override with this one
.opacity(configuration.isPressed ? 0.25 : 1)
.scaleEffect(configuration.isPressed ? 0.92 : 1)
.animation(.easeInOut)
}
}
struct FeedbackButton<Label: View>: View {
let feedbackGenerator: UIImpactFeedbackGenerator
let action: () -> Void
let label: () -> Label
init(style: UIImpactFeedbackGenerator.FeedbackStyle,
action: @escaping () -> Void,
@ViewBuilder label: @escaping () -> Label) {
self.feedbackGenerator = UIImpactFeedbackGenerator(style: style)
self.action = action
self.label = label
}
var body: some View {
Button(action: {
self.feedbackGenerator.impactOccurred()
self.action()
}, label: self.label)
.buttonStyle(FeedbackPreparationButtonStyle(feedbackGenerator: self.feedbackGenerator))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment