简体   繁体   English

SwiftUI - HStack NavigationLink“按钮”分别向两个元素添加 buttonStyle?

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

I'm building my first app and encountering an unclear issue with.buttonStyle within an HStack.我正在构建我的第一个应用程序并在 HStack 中遇到 .buttonStyle 的不明确问题。

This is my code for the.buttonStyle:这是我的 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:我期望第三个 NavigationLink 会看到类似这样的内容:

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!在此先感谢您的帮助!

You would need a HStack which holds both Image and Text.您需要一个包含图像和文本的 HStack。

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

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM