I am currently learning Swift and for an assignment we have to create a simple application. I am trying to get the EditButton() for my master list. I have added the EditButton() to the navigation bar, however, when I click it, the locations in the ForEach go into edit mode, but not the "Test" text, and the environment variable doesn’t update.
This is my current code I am using to test:
import Foundation
import SwiftUI
struct LocationMasterListView: View {
@Environment(\.editMode) var editMode
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest (sortDescriptors: [], animation: .default)
private var locations: FetchedResults<Location>
var body: some View {
List {
Text("Test")
//Check for edit
if (editMode?.wrappedValue == .active){
Text("is editing")
}
else{
Text("not editing")
}
ForEach(locations) {
location in
NavigationLink(destination: LocationDetailView(location: location)){
HStack{
MasterImageView(location: location)
VStack(alignment: .leading){
Text(location.locationName)
Text(location.locationSuburb)
.font(.footnote)
.foregroundColor(.gray)
}
}
}
}.onDelete(perform: deleteLocation)
}.navigationTitle("Favourite Places")
.navigationBarItems(leading: EditButton(), trailing: Button("+"){
addLocation()
})
}
}
The location list item that is created in the ForEach shows the delete button and that works fine, but not the test text, and the if statement stays on "not editing".
>Solution :
The delete button does not appear for "Test" because it is not modified with onDelete
, like your ForEach
is.
To be modified with onDelete
, the view needs to be a DynamicViewContent
, which is how SwiftUI handles editing. But Text
does not conform to that. You can make a DynamicViewContent
by using a ForEach
:
ForEach(0..<1) { _ in
Text("Test")
}.onDelete { _ in
// do something when Test is deleted
}
As for why the "is/not editing" text is not working, see this question. In short, you should use .environment(\.editMode)
and a @State
to track the edit mode.
@State var editMode: EditMode = .inactive
// ...
// modifying the List
.environment(\.editMode, $editMode)