Created
February 20, 2021 20:45
-
-
Save rayfix/11827eaf8acae38a08b2190c0db72cee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ContentView.swift | |
// Slider | |
// | |
// Created by Ray Fix on 2/20/21. | |
// | |
import SwiftUI | |
struct VolumeView: View { | |
@Binding var volume: Int? | |
@State private var value: (CGFloat, enabled: Bool) = (50, true) | |
var body: some View { | |
VStack { | |
if value.enabled { | |
Text("\(Int(value.0))").font(.largeTitle) | |
} | |
else { | |
Text("--").font(.largeTitle) | |
} | |
Slider(value: $value.0, in: 0...100) | |
.disabled(!value.enabled) | |
Toggle("Enabled", isOn: $value.enabled) | |
}.padding() | |
.onAppear() { | |
value.enabled = volume != nil | |
value.0 = CGFloat(volume ?? 19) | |
} | |
.onChange(of: value.0) { v in | |
if value.enabled { | |
volume = Int(v) | |
} | |
else { | |
volume = nil | |
} | |
} | |
.onChange(of: value.enabled) { e in | |
volume = e ? Int(value.0) : nil | |
} | |
} | |
} | |
class Stereo: ObservableObject { | |
@Published var volume: Int? = 22 | |
} | |
struct ContentView: View { | |
@StateObject private var stereo = Stereo() | |
var body: some View { | |
VStack { | |
VolumeView(volume: $stereo.volume) | |
if let v = stereo.volume { | |
Text("Volume: \(v)") | |
} | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment