我创建了一个带有水平堆栈视图(标签、按钮、按钮)的简单列表。每个按钮都有自己的按钮操作,但是当我跑步时,我可以看到点击一个按钮会打印两个操作。断点也出现在这两个动作中。她是我的密码
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")
}
}
需要像这样使用
onTapGesture
代替action
。
Button(action: {}) {
Text("watch")
}
.frame(minWidth: 0, maxWidth: .infinity)
.background(Color.red)
.onTapGesture {
print("watch")
}
使用按钮样式
.buttonStyle(BorderlessButtonStyle())
示例:-
Button(action: {
print("Rate us")
}, label: {
Text("Rate us")
.background(Color.red)
}).buttonStyle(BorderlessButtonStyle())
你也可以使用这种风格:
.buttonStyle(PlainButtonStyle())
您还可以使用适合我的文本和 .onTapGesture,而按钮也有同样的问题:单击部分 / VStack / 2(HStack 按钮)中的一个按钮会执行两个按钮的代码!