我在iOS14.3(Xcode12.3)上有一个SwiftUI的List
,希望在其中的单元格中,当用户点击按钮时能弹出一个Menu
。此外,这些单元格具有onTapGesture
,问题在于该手势也会在按下菜单按钮时被触发。
示例:
List {
HStack {
Text("Cell content")
Spacer()
// Triggers also onTapGesture of cell
Menu(content: {
Button(action: { }) {
Text("Menu Item 1")
Image(systemName: "command")
}
Button(action: { }) {
Text("Menu Item 2")
Image(systemName: "option")
}
Button(action: { }) {
Text("Menu Item 3")
Image(systemName: "shift")
}
}) {
Image(systemName: "ellipsis")
.imageScale(.large)
.padding()
}
}
.background(Color(.systemBackground))
.onTapGesture {
print("Cell tapped")
}
}
如果您点击省略图像,将打开菜单,同时会在控制台上打印出"Cell tapped"
。这对我来说是一个问题,因为在我的实际示例中,我正在折叠单元格,在用户按下菜单按钮时当然不希望发生这种情况。
我发现,当我长按按钮时,手势不会被触发。但在我看来,这不是可接受的用户体验,花了我一段时间才找到自己的方法。
我还注意到,当我用普通的Button
替换Menu
时,单元格的手势在按下时不会被触发(仅适用于BorderlessButtonStyle
或PlainButtonStyle
,否则它根本不活跃)。但我不知道如何从其操作中打开菜单。
List {
HStack {
Text("Cell content")
Spacer()
// Does not trigger cells onTapGesture, but how to open Menu from action?
Button(action: { print("Button tapped") }) {
Image(systemName: "ellipsis")
.imageScale(.large)
.padding()
}
.buttonStyle(BorderlessButtonStyle())
}
.background(Color(.systemBackground))
.onTapGesture {
print("Cell tapped")
}
}