Reputation: 23
I am developing a SwiftUI
application that uses pickers. I have 6 pickers that I want to be able to set the minimum
and maximum
values for. I have a separate view with steppers
to set the minimum
and maximum
of each picker
. All of the variables are stored in the environment. Right now, the pickers do not update when navigating from the settings view back to the main view. They do not change until after you move the pickers. Is there a way to have to pickers minimum and maximum values change when the view navigates back rather than having to move the pickers first?
This is an example of one of my pickers:
Picker(selection: self.$ticket.pick1, label: Text("")) {
ForEach(self.ticket.min1 ... self.ticket.max1, id: \.self) {
Text("\($0)").frame(width: geometry.size.width / 6)
}
}
Here is an example of one of the minimum and maximum steppers:
Text("Pick One").fontWeight(.bold)
Stepper(value: $ticket.min1, in: 1...100, label: {Text("Minimum: \(ticket.min1)")})
Stepper(value: $ticket.max1, in: 1...100, label: {Text("Maximum: \(ticket.max1)")})
Upvotes: 1
Views: 1016
Reputation: 11539
When you need to change a picker
range realtime, you may consider .id()
. The following example can solve this specific question. It may involve other situations in a real complex situation, like data binding. But that's another story.
struct Ticket : Hashable{
var min1 : Int
var max1 : Int
var pick1 : Int
}
struct CoolPickers: View {
@State var ticket: Ticket = Ticket(min1: 1, max1: 10, pick1: 2)
var body: some View {
GeometryReader { geometry in
NavigationView{
VStack{
NavigationLink("Next", destination: SettingPickersView(ticket: self.$ticket))
Picker(selection: self.$ticket.pick1, label: Text("")) {
ForEach(self.ticket.min1 ... self.ticket.max1, id: \.self) {
Text("\($0)")
.frame(width: geometry.size.width / 6)
}
}.id(self.ticket)
}
}
}
}
}
struct SettingPickersView: View {
@Binding var ticket: Ticket
var body: some View {
Group{
Text("Pick One").fontWeight(.bold)
Stepper(value: $ticket.min1, in: 1...100, label: {Text("Minimum: \(ticket.min1)")})
Stepper(value: $ticket.max1, in: 1...100, label: {Text("Maximum: \(ticket.max1)")})
}
}
}
Upvotes: 1