[英]Buttons in SwiftUI List ForEach view trigger even when not "tapped"?
我有以下代碼:
struct ButtonTapTest: View {
let items = [1, 2, 3]
var body: some View {
List {
ForEach(items, id:\.self) { item in
CellTestView()
}
}
}
}
struct CellTestView:View {
var body: some View {
VStack {
Button {
print("TOP")
} label: {
Image(systemName: "play.fill")
.font(.system(size: 40))
.foregroundColor(.red)
}
.border(.red)
Spacer()
Button {
print("BOTTOM")
} label: {
Image(systemName: "play")
.font(.system(size: 40))
.foregroundColor(.red)
}
.border(.yellow)
}
}
}
創建以下屏幕:
問題:
無論我在哪里點擊CellTestView
,都會在單元格中觸發兩個按鈕操作。 我希望單獨觸發單個按鈕操作,每個按鈕僅在其按鈕被點擊時觸發,而不是當我在單元格上的其他任何地方點擊外部時。
您可以在下面的 gif 中看到,我點擊CellTestView
的位置無關緊要,無論我點擊視圖的哪個位置,兩個按鈕操作都會觸發,並且“TOP”和“BOTTOM”日志同時觸發。
如何解決此問題,以便單元格中的兩個按鈕獨立接收點擊,並且僅當點擊位於相關按鈕內時?
我對這個問題的解決方法是將每個按鈕包裝在它自己的 VStack 或 HStack 中。
當您有一個列表時,點擊列表行將觸發兩個按鈕。 嘗試使用此代碼使每個“按鈕”等效,分別觸發。
struct CellTestView: View {
var body: some View {
VStack {
Image(systemName: "play.fill") .font(.system(size: 40)).foregroundColor(.red).border(.red)
.onTapGesture {
print("-----> playFill \(playFill)")
}
Spacer()
Image(systemName: "play") .font(.system(size: 40)).foregroundColor(.red).border(.yellow)
.onTapGesture {
print("--> play \(play)")
}
}
}
}
每當列表行中有多個按鈕時,您需要手動將按鈕樣式設置為.borderless
或.plain
。
CellTestView()
.buttonStyle(.borderless)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.