【问题标题】:SwiftUI - HStack NavigationLink "buttons" adding buttonStyle to both elements seperately?SwiftUI - HStack NavigationLink“按钮”分别向两个元素添加按钮样式?
【发布时间】:2020-06-11 19:13:08
【问题描述】:

我正在构建我的第一个应用,但在 HStack 中遇到了 .buttonStyle 不清楚的问题。

这是我的 .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)
}

}

这是我体内的代码:

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"))

我期望第三个 NavigationLink 会发生类似这样的事情:

Image+text one button

但我得到的是:

Image+text seperated

我试过摆弄,但我似乎无法弄清楚是什么原因造成的。提前感谢您的帮助!

【问题讨论】:

    标签: ios swift iphone swiftui swiftui-navigationlink


    【解决方案1】:

    您需要一个同时包含图像和文本的 HStack。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-11
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      • 2011-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多