Reputation: 1541
import SwiftUI
struct ContentView : View {
var body: some View {
PasswordGeneratorSettings(settingsConfiguration: PasswordGeneratorSettings.Settings.init(passwordLength: 20))
}
}
struct PasswordGeneratorSettings : View {
@State var settingsConfiguration: Settings
struct Settings {
var passwordLength = UInt()
}
var body: some View {
NavigationView {
List {
Slider(value: $settingsConfiguration.passwordLength) { pressed in
Text("Password Length: \(settingsConfiguration.passwordLength)")
}
}.navigationBarTitle(Text("Settings"))
}
}
}
So I'm making a password generator and I want to start off with a slider with a minimum length of 1 and a maximum length of 512 with a label displaying it's value (As an integer) but this is all I got to just try having an updating label on the left of the tableview (List) with the slider on the right but this doesn't even compile.
Too Long Didn't Read: I'm trying to:
Figure out how to set a minimum and maximum value with a Slider
Have a label with the Slider's value (as an integer) on the left side of a tableview cell with the slider on the right side.
And I want to do all of this without UIKit just SwiftUI (and Combine if needed).
Upvotes: 7
Views: 7316
Reputation: 11426
struct BoundsSlider : View {
let min: CGFloat
let max: CGFloat
@Binding var value: CGFloat
@State var lastValue: CGFloat
init (min: CGFloat, max: CGFloat, value: Binding<CGFloat>) {
self.min = min
self.max = max
_value = value
_lastValue = State(initialValue: value.wrappedValue)
}
var body: some View {
Slider(value: Binding.init(get: { () -> CGFloat in return value },
set: { (newValue) in if true { value = newValue; lastValue = newValue } }), in: min...max)
}
}
usage:
BoundsSlider(min: 0.7, max: 5, value: $speed)
Upvotes: 0
Reputation: 40509
This is how you use a slider:
import SwiftUI
struct ContentView : View {
@State var length: Float = 20
var body: some View {
NavigationView {
List {
PasswordGeneratorSettings(length: $length)
}.navigationBarTitle(Text("Settings"))
}
}
}
struct PasswordGeneratorSettings : View {
@Binding var length: Float
var body: some View {
VStack(alignment: .leading) {
Slider(value: $length, in: 1...512, step: 1)
Text("Password Length: \(Int(length))")
}
}
}
Upvotes: 3
Reputation: 1659
Your code doesn't compile because you need to use double in the slider value parameter. You can achieve your requirement using the below code. Slider takes three parameter value, from and through. In simple language, from is minValue, through is maxValue and at any given time "value" will return current value in the slider.
struct PasswordGeneratorSettings : View {
@State var settingsConfiguration: Settings
struct Settings {
var passwordLength: Double = 1.0
}
var body: some View {
NavigationView {
List {
HStack {
Text("Password Length: \(Int(settingsConfiguration.passwordLength))")
Slider(value: $settingsConfiguration.passwordLength, from: 1, through: 512)
}
.padding()
}.navigationBarTitle(Text("Settings"))
}
}
}
Upvotes: 2