I have Picker of style SegmentedPickerStyle(). Now i'm doing some calculation based on picker value, and it's working. But somehow my picker is not changing its selection value if I tap on it. For changing the selection value, i need to swipe over the values.
Another issue is, if i need to calculate TipAmount then first i need to swipe to the picker value and then need to select that value. I don't know why is it happening!!
Here is my View code,
struct ContentView: View {
@ObservedObject var tipViewModel = TipViewModel()
var body: some View {
VStack {
TextField("Enter bill amount", text: $tipViewModel.billAmount)
.textFieldStyle(RoundedBorderTextFieldStyle())
Picker(selection: $tipViewModel.tipPercentage, label: Text("Select tip %")) {
ForEach(tipViewModel.tipChoices, id: \.self) { choice in
//Text("\(self.tipViewModel.tipChoices[choice])")
Text("\(choice)")
}
}.pickerStyle(SegmentedPickerStyle())
.onTapGesture {
self.tipViewModel.calculateTip()
}
Text("Tip Percentage \(tipViewModel.tipPercentage)")
Text(tipViewModel.tipAmount == nil ? "Tip Amount" : "\(tipViewModel.tipAmount!)")
}.padding()
}
}
And here is TipViewModel file,
class TipViewModel: ObservableObject {
@Published var billAmount: String = "" {
didSet{
calculateTip()
}
}
@Published var tipPercentage: Int = 10
@Published var tipAmount: Double = 0
let tipChoices = [10, 15, 20]
let didChange = PassthroughSubject<TipViewModel, Never>()
func calculateTip() {
guard let billAmount = Double(billAmount) else { return }
self.tipAmount = billAmount * Double(tipPercentage) / 100
self.didChange.send(self)
}
}
Any help would be appreciated!!