SwiftUI - HStack NavigationLink "buttons" adding buttonStyle to both elements seperately?

Viewed 393

I'm building my first app and encountering an unclear issue with .buttonStyle within an HStack.

This is my code for the .buttonStyle:

struct GradientBackgroundStyle: ButtonStyle {

func makeBody(configuration: Self.Configuration) -> some View {
    configuration.label
        .foregroundColor(Color.white)
        .font(.title)
        .padding()
        .frame(width: 300)
        .background(LinearGradient(gradient: Gradient(colors: [Color.red, Color.orange]), startPoint: .leading, endPoint: .trailing))
        .cornerRadius(15.0)
        .scaleEffect(configuration.isPressed ? 0.9 : 1.0)
}

}

And this is the code in my body:

var body: some View {
    NavigationView {
        VStack(spacing: 15.0) {
            Divider()
            HStack() {
                NavigationLink(destination: TestView()) {
                    Text("1")
                }.buttonStyle(GradientBackgroundStyle())
        }
        HStack {
            NavigationLink(destination: TestView()) {
                Text("2")
            }.buttonStyle(GradientBackgroundStyle())
        }
        HStack {
            NavigationLink(destination: TestView()) {
                Image(systemName: "star.fill")
                Text("Tasks")
            }.buttonStyle(GradientBackgroundStyle())
        }
        Spacer()
    }
        
    .navigationBarTitle(
            Text("Title"))

What I am expecting to happen for the third NavigationLink is to see something similar like this:

Image+text one button

But what I'm getting is this:

Image+text seperated

I've tried fiddling, but I can't seem to figure out what is causing this. Thanks in advance for any help!

1 Answers

You would need a HStack which holds both Image and Text.

      HStack {
          NavigationLink(destination: TestView()) {
            HStack {
              Image(systemName: "star.fill")
              Text("Tasks")
            }
          }.buttonStyle(GradientBackgroundStyle())
      }

enter image description here

Related