I created a multi wheel picker in swiftUI and I'm my use case the user will set time values utilizing the picker.
I have created the picker and everything works as expected however I am not able to access the computed value which return the user selected time as a Sting. I know I should use @Binding however I have been banging my head against the wall for hours on this.
View for each individual column
struct HoursPickerColumn : View {
let range : ClosedRange<Int>
@Binding var selection : Int
var body: some View {
Picker("" ,selection: $selection) {
ForEach(range, id: \.self) { value in
Text("\(value)")
}
}.pickerStyle(.wheel)
.labelsHidden()
.frame(width: 50,height: 80)
.clipped()
}
}
Hours Picker View code
struct HoursPickerView: View {
@State private var hoursFirstDigit = 0
@State private var hoursSecondDigit = 0
@State private var hoursThirdDigit = 0
@State private var hoursForthDigit = 0
@State private var hoursLastDigit = 0
@State private var minutesFirstDigit = 0
@State private var minutesLastDigit = 0
@Binding var time : String
private var selectedTimeAsString : String {
let hours = [hoursFirstDigit,hoursSecondDigit,hoursThirdDigit,hoursForthDigit,hoursLastDigit].map{"\($0)"}
let minutes = [minutesFirstDigit,minutesLastDigit].map{"\($0)"}
let hoursJoined = hours.joined()
let minutesJoined = minutes.joined()
let stringValue = hoursJoined + ":" + minutesJoined
return stringValue
}
var body: some View {
VStack {
HStack(spacing : -15){
HoursPickerColumn(range: 0...9, selection: $hoursFirstDigit)
HoursPickerColumn(range: 0...9, selection: $hoursSecondDigit)
HoursPickerColumn(range: 0...9, selection: $hoursThirdDigit)
HoursPickerColumn(range: 0...9, selection: $hoursForthDigit)
HoursPickerColumn(range: 0...9, selection: $hoursLastDigit)
Text(":")
.font(.title)
.padding(.horizontal)
HoursPickerColumn(range: 0...5, selection: $minutesFirstDigit)
HoursPickerColumn(range: 0...9, selection: $minutesLastDigit)
}.frame(width: 280, height: 50)
.clipped()
.background(
RoundedRectangle(cornerRadius: 10)
.foregroundStyle(.white.shadow(.inner(color: .gray, radius: 1)))
)
Text(selectedTimeAsString).bold()
}
}
}
The above code yields the following
I need to access the string value from the containerView or any other containing view. I considered creating a TimeValue model with two properties var hours : Int
and var minutes : Int
and Have a @Binding
property inside the HoursPickerView and let the model object handle splitting the Int into individual digits then binding those values to the individual columns. But all the above seems like overkill just to retrieve a value that I already have.
Any guidance or ideas would be highly appreciated.