简体   繁体   中英

SwiftUI onDelete cannot detect tap when onTapGesture is added

I am developing an iOS app with list by SwiftUI. I am implementing .onDelete to enable user to delete the rows. However, I have found that when I add a .onTapGesture to the VStack View containing the List, the onDelete function is not called when the user tapped the "Delete" button after slide the row left. However, it stills works when the user slide the row to the left side to delete this. It seems that the .onTapGesture blocks .onDelete to receive user input. How to solve this?

NavigationView {
    VStack(alignment: .leading) {
        List {
            ForEach(things) { thing in
                Text(thing)
            }
            .onDelete(perform: { indexSet in
                things.remove(atOffsets: indexSet)
            })
        }
        .listStyle(SidebarListStyle())
        }
    .onTapGesture {
    }
}

Here is some code that can show my problem.

This is probably useless and very hacky but... If you must have an area that is tappable, you could place everything in a ZStack and put a random view over the List and make that tappable. Then you could set a good amount of padding to free the area where the delete button would be tapped, like this:

        NavigationView {
        ZStack {
            List {
                ForEach(things, id: \.self) { thing in
                    Text(thing)
                    }
                        .onDelete(perform: { indexSet in
                            things.remove(atOffsets: indexSet)
                        })
                    }
                        .zIndex(2)
                        .listStyle(SidebarListStyle())
            
                Rectangle()
                    .zIndex(3)
                    .fill(Color.red)
                    .padding(.trailing, 80)
                    .allowsHitTesting(true)
                    .onTapGesture {
                        print("Blocking you")
                    }
                }
        }

I put the color in so you can see exactly where you are working, the code above would give you a look like this:

Tappable Rectangle on List

When you're happy with the area that the rectangle covers, you can just set the Opacity to a very small amount, just by replacing the color with

.opacity(0.000001)

or something. Unfortunately taps don't work with Color.clear or hidden() modifiers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM