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

3

5

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

Ocher answered 7/10, 2021 at 19:9 Comment(0)
I
10

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.

Inkster answered 8/10, 2021 at 0:1 Comment(3)
For some reason this makes the view half-transparent in the preview but it works in the actual app, thank youOcher
Nope. This did not work. same result as OPGaal
Genius. FYI this also works for the simple Link view which is what I was looking to remove the padding of developer.apple.com/documentation/swiftui/linkAlmire
W
2

To take away the unwanted border introduced by the NavigationLink, simply apply buttonStyle as plain to the NavigationLink like so:

NavigationLink(destination: DestinationView()) {
                            ExtractedView()
                        }.buttonStyle(.plain)
Wimsatt answered 24/9, 2022 at 10:14 Comment(0)
C
2

@Adam 's solution seems to doesn't be enough. Try the following code:

NavigationLink(destination: Text("")) {
         Text("Dummy Text")
           .font(.title3)
           .foregroundColor(.white)
           .background(Color.blue)
     }
     .buttonStyle(.plain)
     .listRowInsets(EdgeInsets())

Chintz answered 26/1, 2023 at 15:39 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.