Not Allowing Row Selection in List

In UIKit, it's just the matter of setting table view's allowsSelection to false if you don't want to allow selection. If each row has a button, it can still be clicked on. Can we do that in SwiftUI?

I have the following simple SwiftUI project.

import SwiftUI

struct ContentView: View {
	@State private var fruits = ["Apple", "Banana", "Mango", "Watermelon", "Pineapple", "Strawberry", "Orange"]
	@State private var isEditable = true

	var body: some View {
		List {
			ForEach(fruits, id: \.self) { fruit in
				HStack {
					Text(fruit)
						.onDrag {
							return NSItemProvider()
						}
					Spacer()
					Button {
						print("Hello")
					} label: {
						Text("Tap me")
					}
				}
			}
			.onMove(perform: move)
		}
		.onTapGesture(perform: {
			return
		})
		.listStyle(.plain)
	}

	func move(from source: IndexSet, to destination: Int) {
		fruits.move(fromOffsets: source, toOffset: destination)
		withAnimation {
			isEditable = false
		}
	}
}

The tap gesture prevents row interaction. So I won't even be able to tap the button. How can I disable row selection while allowing interaction inside the list row?

List {
}
.onAppear {
	UITableView.appearance().allowsSelection = false
	UITableViewCell.appearance().selectionStyle = .none
}

The lines of code above don't work, either.

Thanks.

Answered by Engineer in 725762022

Try setting an explicit button style on your button. This should prevent it's action from being bubbled up as the overall row action.

HStack {
    Text(fruit)
        .onDrag {
            return NSItemProvider()
        }
    Spacer()
    Button {
        print("Hello")
    } label: {
        Text("Tap me")
    }
    .buttonStyle(.borderless)
}
Accepted Answer

Try setting an explicit button style on your button. This should prevent it's action from being bubbled up as the overall row action.

HStack {
    Text(fruit)
        .onDrag {
            return NSItemProvider()
        }
    Spacer()
    Button {
        print("Hello")
    } label: {
        Text("Tap me")
    }
    .buttonStyle(.borderless)
}
Not Allowing Row Selection in List
 
 
Q