HStack 中的两个按钮互相作用

Sha*_*ikh 15 ios swiftui

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

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")
    }
}
Run Code Online (Sandbox Code Playgroud)

Sha*_*ikh 19

需要使用onTapGesture而不是action这样的方式。

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

  • 我有同样的问题,但你的解决方案对我不起作用 (2认同)
  • 这确实有效,但确实令人沮丧。我必须使用它在表单行中有两个按钮。 (2认同)