swiftswiftui

How to disable interactions on List cells while keeping buttons inside interactive in SwiftUI?


I have a SwiftUI app that displays a social feed with posts in a List. Each post contains buttons that need to remain interactive, but I don't want the entire cell to be tappable.

I've tried different approaches like .disabled(true) on the list (which also disables the buttons), .allowsHitTesting(false) on individual elements, and .onTapGesture {} to absorb taps, but none work as expected.

Thanks


    List() {
        ForEach(posts, id: \.self) { post in
            PostView()
                .onAppear {
                    if post == posts.last {
                        loadMorePost()
                    }
                }
                .listRowInsets(EdgeInsets())
                .alignmentGuide(.listRowSeparatorLeading) { vd in
                    return 0
                }
        }
    }
    .listStyle(.plain)
    
    struct PostView: View {
        var body: some View {
            VStack(spacing: 10) {
                PostHeaderView(image: Image("clovis"), userName: "Stephane", userIdentifier: "stephane_")
                PostContentView()
            }
            .padding(20)
        }
    }
    
    struct PostContentView: View {
        var body: some View {
            VStack(alignment: .leading, spacing: 10) {
                // Post content
                Text("Coiffeuse")
                    .font(.headline)
                
                Text("It is a long established fact that a reader will be distracted...")
                    .font(.caption)
                
                HStack(spacing: 20) {
                    PriceContainerView()
                    Spacer()
                    HStack(spacing: 2) {
                        Image(systemName: "eyes")
                        Text("2K")
                    }
                    // This button needs to remain interactive
                    Button(action: { print("Save To Later") }) {
                        Image(systemName: "bookmark")
                            .foregroundStyle(.mediumGray)
                    }
                }
            }
        }
    }
```

Solution

  • Try adding

    .buttonStyle(.plain)
    

    to your bookmark button.

    Its definitely very obscure and unintuitive but it somehow does the trick.