Skip to content

Instantly share code, notes, and snippets.

@ZevEisenberg
Last active December 11, 2021 02:08
Show Gist options
  • Save ZevEisenberg/05c417256aa10e120c0619ab9a014226 to your computer and use it in GitHub Desktop.
Save ZevEisenberg/05c417256aa10e120c0619ab9a014226 to your computer and use it in GitHub Desktop.
import SwiftUI
struct ContentView: View {
var body: some View {
NicerButton(action: {}, label: { isPressed in
Text("Rabbit Season")
.foregroundColor(Color.white)
.frame(width: 200)
.padding()
.background(Color.blue.brightness(isPressed ? -0.3 : 0))
})
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
import SwiftUI
private struct IsPressedPreferenceKey: PreferenceKey {
static var defaultValue = false
static func reduce(value: inout Bool, nextValue: () -> Bool) {
value = value || nextValue()
}
}
private struct NicerButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.preference(key: IsPressedPreferenceKey.self, value: configuration.isPressed)
}
}
public struct NicerButton<Label>: View where Label: View {
private let action: () -> Void
private let labelBuilder: (_ isPressed: Bool) -> Label
@State private var isPressed: Bool = false
public init(action: @escaping () -> Void, @ViewBuilder label labelBuilder: @escaping (_ isPressed: Bool) -> Label) {
self.action = action
self.labelBuilder = labelBuilder
}
public var body: some View {
Button(action: action) {
labelBuilder(isPressed)
}
.buttonStyle(NicerButtonStyle())
.onPreferenceChange(IsPressedPreferenceKey.self) { isPressed in
self.isPressed = isPressed
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment