Skip to content

Instantly share code, notes, and snippets.

@dfrobison
Created October 13, 2020 21:01
Show Gist options
  • Save dfrobison/c0fd76a6e47cef87787b45fab28cf4ef to your computer and use it in GitHub Desktop.
Save dfrobison/c0fd76a6e47cef87787b45fab28cf4ef to your computer and use it in GitHub Desktop.
[Move onChange into binding]
import SwiftUI
struct ContentView: View {
@State private var rating = 0.0
var body: some View {
Slider(value: $rating.onChange(sliderChanged))
}
func sliderChanged(_ value: Double) {
print("Rating changed to \(value)")
}
}
extension Binding {
func onChange(_ handler: @escaping (Value) -> Void) -> Binding<Value> {
Binding(
get: { self.wrappedValue },
set: { newValue in
self.wrappedValue = newValue
handler(newValue)
}
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment