SwiftUI: How to center NavigationLink inside of a Form

888 views Asked by At

Apologies if this has been asked/answered; I am trying to present a NavigationLink inside of a form, but would like it to be centered. I can do this with a Button using HStack and Spacers; the NavigationLink is a tat more stubborn:

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            Form {
                HStack {

                    //BUTTON CENTERS WITH SPACERS

                    Spacer()
                    Button(action: {}, label: {
                        Text("Button")
                    })
                    Spacer()
                }
                
                HStack {

                    //NAVIGATIONLINK IGNORES SPACERS

                    Spacer()
                    NavigationLink(
                        destination: Text("Destination"),
                        label: {
                     Text("Navigate")    
                    })
                    Spacer()
                }
            }
        }
    }
}

NavigationLink will not center in Form

1

There are 1 answers

0
xTwisteDx On BEST ANSWER

One way that I like to do this is by creating an empty navigation link.

@State var someBoolBinding = false

//Body

NavigationLink(destination: YourDestView(), isActive: $someBoolBinding) {}

Then create a custom button with a toggle.

Button("Go Here") {
   someBoolBinding.toggle()
}

You can use any button, even custom ones, or even an onTapGesture, just by changing that boolean value. From there it's as simple as centering as you would any other element and you don't have to rely on the "Navigation Link" style that you're being presented with. Alternatively you can do something like this.

 NavigationLink(destination: RegisterWithEmailView(), isActive: $someBoolBinding) {
                        Button("Go To some View", action: {
                            someBoolBinding.toggle()
                        })
                    }