SwiftUI - delete row in list with context menu - UI glitch

后端 未结 2 1873
夕颜
夕颜 2021-02-10 16:50

I\'ve a array of items displayed using List in my SwiftUI View. I tired to add a contextMenu to delete individual items in the List<

相关标签:
2条回答
  • 2021-02-10 17:19

    It’s an issue with SwiftUI, hopefully Apple fix it in the next major release. For now you can solve the issue by adding a small delay before actions are performed in your context button action:

    DispatchQueue.main.asyncAfter(deadline: .now() + 0.7){
        //delete row
    }
    
    0 讨论(0)
  • 2021-02-10 17:21

    It goes from List, unfortunately ListStyle protocol has any public API. The only way I see now, is mimic List with ScrollView

    import SwiftUI
    
    struct ContentView: View {
    
        @State var cars = ["Tesla", "Mercedes", "Audi", "Tata", "Jaguar"]
        var body: some View {
            ScrollView {
                ForEach(cars, id: \.self) { car in
                    VStack(alignment: .leading, spacing: 0) {
                        HStack {
                            Text(car).padding()
                            Spacer()
                        }
                        .contextMenu {
                            Button(action: {
                                if let index = self.cars.firstIndex(of: car) {
                                        self.cars.remove(at: index)
                                }
                            }, label: {
                                HStack {
                                    Text("Delete")
                                    Spacer()
                                    Image(systemName: "trash")
                                }
                            })
                        }
                        Divider().padding(.leading)
                    }.padding(.bottom, 0) // set -4 to be symetric
                }
            }
        }
    }
    

    with the following result

    0 讨论(0)
提交回复
热议问题