Search code examples
swiftuiswiftui-navigationlink

SwiftUI NavigationLink Only Works For Text And Images


I have the following code

NavigationLink(destination: Destination(), label: {
    HStack {
        VStack(alignment: .leading) {
            Text("some text")
                .font(.title3)
                .fontWeight(.semibold)
            
            HStack {
                Circle()
                    .foregroundColor(.black)
                    .frame(width: 15)
                Text("some text")
                    .font(.headline)
                    .fontWeight(.semibold)
            }
            .padding(.top, -10)
        }
        .frame(
            maxWidth: .infinity,
            alignment: .topLeading
        )
        AsyncImage(url: URL(string: "some-link.com")!)
    }
})
.buttonStyle(PlainButtonStyle())

clicking on the Text and Image will let me navigate to the Destination() but the white space inside the HStack won't let me go to Destination. Is there a way to get this to work?


Solution

  • Just add the .contentShape() modifier at the bottom of the HStack, using for example a rectangle shape. In this case, the whole rectangle wrapping the HStack will be tappable.

    Like this:

    NavigationLink(destination: Destination(), label: {
        HStack {
            VStack(alignment: .leading) {
                Text("some text")
                    .font(.title3)
                    .fontWeight(.semibold)
                
                HStack {
                    Circle()
                        .foregroundColor(.black)
                        .frame(width: 15)
                    Text("some text")
                        .font(.headline)
                        .fontWeight(.semibold)
                }
                .padding(.top, -10)
            }
            .frame(
                maxWidth: .infinity,
                alignment: .topLeading
            )
            AsyncImage(url: URL(string: "some-link.com")!)
        }
        .contentShape(Rectangle())       // <- Here!
    })
    .buttonStyle(PlainButtonStyle())