[ad_1]
Utilizing id: .self inside a Checklist or ForEach is a harmful concept in SwiftUI. The system makes use of it to establish what it expects to be distinctive components. However, as quickly as you progress the slider, you’ve a change of ending up with a tip worth that is the same as one other worth within the checklist. Then, SwiftUI will get confused about which factor is which.
To repair this, you should utilize objects with really distinctive IDs. You must also attempt to keep away from utilizing indexes to consult with sure objects within the checklist. I’ve used checklist bindings to keep away from that difficulty.
struct Tip : Identifiable {
var id = UUID()
var tip : Double
}
class SettingsViewModel: ObservableObject {
@Printed var selectedTips : [Tip] = [
.init(tip:10.0),
.init(tip:15.0),
.init(tip:18.0),
.init(tip:20.0),
.init(tip:25.0)
]
func addTip() {
selectedTips.append(.init(tip:0.0))
selectedTips = selectedTips.sorted(by: { a, b in
a.tip < b.tip
})
}
func removeTip(id: UUID) {
selectedTips = selectedTips.filter { $0.id != id }
}
}
struct SettingsTipsView: View {
@StateObject var mannequin = SettingsViewModel()
var physique: some View {
Checklist {
HStack {
Textual content("Edit Recommended Ideas")
.font(.title2)
.fontWeight(.semibold)
Spacer()
if(mannequin.selectedTips.rely < 5) {
Button(motion: { mannequin.addTip() }, label: {
Picture(systemName: "plus.circle.fill")
.renderingMode(.unique)
.font(.title3)
.padding(.horizontal, 10)
})
.buttonStyle(BorderlessButtonStyle())
}
}
ForEach($mannequin.selectedTips, id: .id) { $tip in
HStack {
Textual content("(tip.tip, specifier: "%.0f")%")
.body(width: 50) //In any other case, the width modifications whereas shifting the slider. You can get fancier and attempt to use alignment guides for a extra strong resolution
Slider(worth: $tip.tip, in: 1...99, label: { Textual content("Label") })
if(mannequin.selectedTips.rely > 1) {
Button(motion: { mannequin.removeTip(id: tip.id) }, label: {
Picture(systemName: "minus.circle.fill")
.renderingMode(.unique)
.font(.title3)
.padding(.horizontal, 10)
})
.buttonStyle(BorderlessButtonStyle())
}
}
}
}
}
}
[ad_2]
