Hello!
I want to programmatically set the editMode in SwiftUI for a view as soon as it appears. However, I have read a lot now but it only works via the EditButton - but not programmatically. I'm using the simulator for this example and Xcode Version 15.4.
struct EditTodos: View {
@State private var editMode = EditMode.inactive
@State var content = ["apple", "banana", "peanut"]
var body: some View {
NavigationStack {
List {
ForEach(content, id: \.self) { item in
Text(item)
}
.onDelete { _ in }
.onMove { _, _ in }
}
.onAppear {
editMode = .active // note: not working, why??
}
.navigationBarItems(
trailing: HStack(spacing: 20) {
EditButton()
}
)
}
}
}
#Preview {
EditTodos()
}
Thanks for your post.
Please add the .environment(\.editMode, $editMode)
into your code and it will work.
var body: some View {
NavigationStack {
List {
ForEach(content, id: \.self) { item in
Text(item)
}
.onDelete { _ in }
.onMove { _, _ in }
}
.environment(\.editMode, $editMode)
.onAppear {
editMode = .active // note: not working, why??
}
.navigationBarItems(
trailing: HStack(spacing: 20) {
EditButton()
}
)
}
}
https://developer.apple.com/documentation/swiftui/environmentvalues/editmode
Albert Pascual Worldwide Developer Relations.