Skip to content

Instantly share code, notes, and snippets.

@dfrobison
Created October 13, 2020 21:01
Show Gist options
  • Select an option

  • Save dfrobison/c0fd76a6e47cef87787b45fab28cf4ef to your computer and use it in GitHub Desktop.

Select an option

Save dfrobison/c0fd76a6e47cef87787b45fab28cf4ef to your computer and use it in GitHub Desktop.

Revisions

  1. dfrobison created this gist Oct 13, 2020.
    25 changes: 25 additions & 0 deletions OnChangeBinding.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    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)
    }
    )
    }
    }