1

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

4

1 回答 1

0

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()
                        })
                    }
于 2021-04-22T01:08:55.160 回答