【问题标题】:SwiftUI: Conditional onDeleteSwiftUI:有条件的 onDelete
【发布时间】:2020-10-05 17:26:40
【问题描述】:

我正在尝试创建一个仅允许用户在进入编辑模式后删除的列表。我试图尝试在 onDelete 修饰符中使用三元运算,但无法弄清楚。有什么建议吗?

这是我的代码:

struct ContentView: View {
    @State private var stuff = ["First", "Second", "Third"]
    @State private var check = false
    
    var body: some View {
        Form {
            Button(action: { check.toggle() }, label: { Text(check ? "Editing" : "Edit") })
            
            ForEach(0..<stuff.count) { items in
                Section{ Text(stuff[items]) }
            }
             .onDelete(perform: self.deleteItem)
               
        }
    }
    
    private func deleteItem(at indexSet: IndexSet) {
        self.stuff.remove(atOffsets: indexSet)
    }
}

【问题讨论】:

    标签: swiftui


    【解决方案1】:

    我假设您正在寻找以下内容

    var body: some View {
        Form {
            Button(action: { check.toggle() }, label: { Text(check ? "Editing" : "Edit") })
            
            ForEach(0..<stuff.count) { items in
                Section{ Text(stuff[items]) }
            }
             .onDelete(perform: self.deleteItem)
             .deleteDisabled(!check)             // << this one !!
        }
    }
    

    【讨论】:

      【解决方案2】:
      struct ContentView: View {
          @State private
          var stuff = ["First", "Second", "Third"]
          var body: some View {
              NavigationView {
                  Form {
                      ForEach(0..<stuff.count) { item in
                          Section {
                              Text(stuff[item])
                          }
                      }
                      .onDelete(
                          perform: delete)
                  }
                  .navigationBarItems(
                      trailing:
                          EditButton()
                  )
                  .navigationTitle("Test")
              }
          }
      }
      
      extension ContentView {
          private func delete(at indexSet: IndexSet) {
              stuff.remove(atOffsets: indexSet)
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-06
        • 1970-01-01
        • 2020-03-18
        • 2021-03-12
        • 1970-01-01
        • 2020-01-03
        • 1970-01-01
        • 2020-11-04
        相关资源
        最近更新 更多