I’ve a Checklist()
that I need to replace merchandise’s textual content when contextMenu
button is tapped.
When the button is tapped a @Revealed
worth is up to date. I hearken to worth modifications with onReceive
and if that worth is true the record merchandise the place I lengthy pressed to convey the contextMenu
and faucet the button ought to replace its textual content.
The problem is that each one the objects from the record are up to date. So onReceive
is hit for each component from the record. In a technique I perceive as a result of components are populated in ForEach
though my expectation was to replace just one merchandise.
The behaviour I am making an attempt to copy is from Notes app while you lengthy press a Observe and faucet Lock Observe
. On that motion the lock is utilized just for the chosen Observe.
I attempted to seize the chosen index however once more the onReceive
is triggered for each merchandise from the record.
Methods to outline a customized modifier like onDelete
that deletes on the proper IndexSet
or a operate that may take the IndexSet
and apply the modifications I must that index?
Right here is the code I am making an attempt to unravel.
import SwiftUI
class MyPublish: ObservableObject {
@Revealed var publish = false
}
struct Ocean: Identifiable {
let identify: String
let id = UUID()
var hasPhoto: Bool = false
}
struct OceanDetails: View {
var ocean: Ocean
var physique: some View {
Textual content("(ocean.identify)")
}
}
struct ContentView: View {
@EnvironmentObject var myPublish: MyPublish
@State personal var oceans = [
Ocean(name: "Pacific"),
Ocean(name: "Atlantic"),
Ocean(name: "Indian"),
Ocean(name: "Southern"),
Ocean(name: "Arctic")
]
var physique: some View {
NavigationView {
Checklist() {
ForEach(Array(oceans.enumerated()), id: .component.id) { (index,ocean) in
NavigationLink(vacation spot: OceanDetails(ocean: ocean)) {
ocean.hasPhoto ? Textual content(ocean.identify) + Textual content(Picture(systemName: "picture")) : Textual content("(ocean.identify)")
}
.contextMenu() {
Button("Publish") {
myPublish.publish.toggle()
}
}
.onReceive(myPublish.$publish) { publish in
if publish {
oceans[index].hasPhoto.toggle()
myPublish.publish = false
}
}
}
.onDelete(carry out: removeRows)
}
}
}
func removeRows(at offsets: IndexSet) {
withAnimation {
oceans.take away(atOffsets: offsets)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environmentObject(MyPublish())
}
}
That is only a replication from my app. I need to perceive how this onReceive
is working or whether it is a good suggestion to use it on ForEach
. I attempted to maneuver it on Checklist()
degree however I haven’t got entry anymore to index that I get from the loop.
Any assist can be a lot appreciated.