【问题标题】:Two Buttons inside HStack taking action of each otherHStack 中的两个按钮互相作用
【发布时间】:2020-02-19 05:32:32
【问题描述】:

我创建了一个带有水平堆栈视图(标签、按钮、按钮)的简单列表。每个按钮都有自己的按钮动作,但是当我运行时,我可以看到点击一个按钮会打印两个动作。断点也出现在这两个动作中。她是我的密码

var body: some View {
    NavigationView {
        List {
            ForEach(self.heroViewModel.heros, id: \.self) { hero in
                Section(header: Text(hero.name)) {
                    ForEach(hero.movies, id: \.self) { movieName in
                        HStack {
                            Text(movieName)
                                .onTapGesture {
                                    return
                            }.frame(width: 150, height: 30, alignment: .leading)
                            Spacer()

                            Button(action: {
                                print("Rate us")
                            }, label: {
                                Text("Rate us")
                                    .background(Color.red)
                                }).padding()

                            Spacer()
                            Button(action: {
                                print("watch me")
                            }, label: {
                                Text("Watch")
                                    .background(Color.red)
                                }).padding()
                        }

                    }
                }
            }
        }.navigationBarTitle("Heros List")
    }
}

【问题讨论】:

  • 我真的希望这只是一个错误(而不是一些疯狂的功能),但我也遇到了,并且列出的解决方案有效。
  • 从 iOS 14、SwiftUI 2 开始,这种行为仍然存在。此外,我不确定为什么在 HStack 中点击一个按钮会使整个 HStack 改变其背景颜色。

标签: ios swiftui


【解决方案1】:

需要像这样使用onTapGesture而不是action

Button(action: {}) {
    Text("watch")
}
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color.red)
.onTapGesture {
    print("watch")
}

【讨论】:

  • 我有同样的问题,但你的解决方案对我不起作用?
  • 您面临什么问题?你能和我分享你的代码吗? @Werb
  • 这行得通,但真的令人沮丧。我必须使用它在表单行中有两个按钮。
【解决方案2】:

使用按钮样式

.buttonStyle(BorderlessButtonStyle())

例子:-

Button(action: {
     print("Rate us")
     }, label: {
     Text("Rate us")
     .background(Color.red)
}).buttonStyle(BorderlessButtonStyle())

【讨论】:

    【解决方案3】:

    你也可以使用这种风格:

    .buttonStyle(PlainButtonStyle())

    【讨论】:

      猜你喜欢
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 2019-08-07
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多