How can I place a NavigationLink in the top right corner of a view?

68 Views Asked by At

I'm trying to place a SwiftUI NavigationLink in a view, and I'm having some trouble achieving both of these things:

  1. Place a NavigationLink in the top right corner of a view.
  2. Have the "tap location" for the NavigationLink be exactly where the label is (and active across the whole label).

This code achieves #2, but not #1:

NavigationLink(destination: OverviewView()) {
  OverviewButton()
}

Whereas this code achieves #1, but not #2 (the tap location is slightly offset (a few pixels to the right and down) from the NavigationLink

HStack {
    Spacer()
    VStack {
        NavigationLink(destination: OverviewView()) {
            OverviewButton().padding(75)
        }
        Spacer()
    }
}

And this is the code for OverviewButton

ZStack {
    RoundedRectangle(cornerRadius: 25).fill(.gray.opacity(0.5))
    Label(
        title: { Text("Overview").font(.headline) },
        icon: { Image(systemName: "arrowshape.forward.circle").resizable()
                .scaledToFit()
            .frame(width: 20, height: 20) }
    ).labelStyle(.titleAndIcon).foregroundColor(.white)
}.frame(width: 130, height: 30)

How can I make a NavigationLink that accomplishes both tasks?

1

There are 1 best solutions below

3
Chetan A On

Did you mean something like this:

struct ContentView: View {
    var body: some View {
        VStack {
            HStack {
                Spacer()
                NavigationLink(destination: OverviewView()) {
                    OverviewButton()
                }
                .buttonStyle(PlainButtonStyle()) // Remove the default button style to avoid extra padding
                .padding(.trailing, 16) // Adjust the padding as needed
            }
            Spacer()//place the spacer as per your UI need
        }
    }
}

struct OverviewButton: View {
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 25).fill(Color.gray.opacity(0.5))
            Label(
                title: {
                    Text("Overview")
                        .font(.headline)
                        .foregroundColor(.white)
                },
                icon: {
                    Image(systemName: "arrowshape.forward.circle")
                        .resizable()
                        .scaledToFit()
                        .frame(width: 20, height: 20)
                        .foregroundColor(.white)
                }
            )
        }
        .frame(width: 130, height: 30)
    }
}

enter image description here