Search code examples
swiftuipaddingswiftui-navigationlink

SwiftUI: NavigationLink causes unwanted padding in minimal 10-line-example


When wrapping views in a NavigationLink to create a Master-Detail flow, the NavigationLink appears to add padding (red) that I don't want.

enter image description here enter image description here

If I comment out the NavigationLink, everything looks correct (picture on the right). That however of course makes my views unclickable.

What can I do to remove the red padding that occurs when I render this on the Watch?

This is the code that I run:

struct ContentView: View {
    
    let testArray = [1,2,3,4,5]
    
    var body: some View {
        
        ScrollView {
            VStack {
                ForEach(testArray, id: \.self) { element in
                    
                    NavigationLink(destination: Text("")) {
                        Text("BB . . . . . . . . . . . . . . . . . . . . . . .")
                            .font(.title3)
                            .foregroundColor(.white)
                            .background(Color.blue)
                    }.background(Color.red) //has all the unwanted padding
                    
                }
            }.background(Color.black)
        }.background(Color.gray)
    }
}

I found a few good hints at How to show NavigationLink as a button in SwiftUI however doing ZStack/.background tricks only leaves a ~30px strip that is clickable, it does not fill the whole ZStack in that case.

I figured out the padding seems to be a static 8px. So what I'm doing now is .padding(.all, -8) hoping for a better solution to come


Solution

  • Apply .buttonStyle(PlainButtonStyle()) to your NavigationLink to remove the padding and background. You’ll also lose a button’s default styling, obviously, so you’ll have to recreate it if you want it.