当列表中的最后一项被删除时,如何手动关闭编辑模式?

问题描述 投票:0回答:2

我的应用程序中有一个简单的视图,显示清单列表。当没有清单时,我会显示占位符视图。

我遇到的问题是,当我删除列表中的最后一项时,EditButton() 不会切换回“编辑”;即使列表是空的,它仍然显示“完成” 如果我添加一个新项目,列表会再次出现,但处于编辑模式(糟糕的用户体验)。

有没有办法在删除列表中的最后一项后手动“关闭”编辑模式?

图片:https://i.stack.imgur.com/lE1yu.png

import SwiftUI

struct HomeView: View {
    // MARK: - PROPERTIES
    @EnvironmentObject var checklistsVM: Store
    @StateObject var homeVM: HomeViewModel = HomeViewModel()
    
    
    // MARK: - BODY
    var body: some View {
        NavigationView {
            Group {
                if(checklistsVM.checklists.isEmpty) {
                    EmptyList()
                        .environmentObject(homeVM)                    
                } else {
                    HomeListResults()
                        .environmentObject(homeVM)
                }
            }
            .navigationBarTitle("Checklists", displayMode: .large)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    EditButton()
                }
            }
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }
}
ios swift listview swiftui edit
2个回答
2
投票

您可以使用

Environment
值关闭编辑模式:

    @Environment(\.editMode) private var editMode

    var body: some View {
        Button("Turn off edit mode") {
            editMode?.wrappedValue = .inactive
        }
    }

0
投票

您可以通过与 @State 变量绑定来启用对

editMode
的手动控制。

struct ContentView: View {
    @State var fruits = ["Apple", "Banana"]
    @State var editMode: EditMode = .inactive
    
    var body: some View {
        NavigationStack {
            List {
                ForEach(fruits, id: \.self) { fruit in
                    Text(fruit)
                }
                .onDelete { _ in
                    print("Delete")
                }
            }
            .environment(\.editMode, $editMode)
            .toolbar {
                ToolbarItem(placement: .topBarLeading) {
                    Button(action: {
                    // Here's how you can change the editing state
                        withAnimation {
                            editMode = .inactive
                        }
                    }, label: {
                        Text("Cancel Editing")
                    })
                }
                
                ToolbarItem(placement: .topBarTrailing) {
                    Button(action: {
                        withAnimation {
                            editMode = .active
                        }
                    }, label: {
                        Text("Edit")
                    })
                }
            }
        }
    }
}

您可以观察您的

checklistsVM.checklists
值来检查它何时为空,然后相应地禁用您的编辑模式,就像我在“取消编辑”按钮操作中所做的那样。

© www.soinside.com 2019 - 2024. All rights reserved.