Skip to content

Instantly share code, notes, and snippets.

@andr3a88
Created August 8, 2023 10:57
Show Gist options
  • Save andr3a88/8274c9685e07389576caddff6d1c095e to your computer and use it in GitHub Desktop.
Save andr3a88/8274c9685e07389576caddff6d1c095e to your computer and use it in GitHub Desktop.
SwiftUI: Two way binding with @State and @binding
import SwiftUI
import PlaygroundSupport
struct ContentView: View {
@State private var sliderValue: CGFloat = 0
private var minSliderValue: CGFloat = 10
private var maxSliderValue: CGFloat = 100
var body: some View {
VStack {
Text("Slider value: \(Int(sliderValue))").foregroundColor(.blue).font(.title3)
MySlider(value: $sliderValue, minValue: minSliderValue, maxValue: maxSliderValue)
}.padding(20)
}
}
struct MySlider : View {
@Binding var value: CGFloat
var minValue: CGFloat
var maxValue: CGFloat
var body: some View {
HStack {
Text("\(Int(minValue))")
.foregroundColor(.blue)
Slider(value: $value, in: minValue...maxValue, step: 1)
Text("\(Int(maxValue))")
.foregroundColor(.blue)
}.frame(width: 300)
.padding()
}
}
PlaygroundPage.current.setLiveView(ContentView())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment