我正在制作一个组件。该组件用于显示标签列表。我希望当用户长按标签时会在标签上弹出一个上下文菜单。像这样:
您会看到,上下文菜单显示在标签的容器上,而不是标签上。
VStack(alignment: .leading) {
ForEach(groupedItems, id: \.self) { itms in
HStack {
ForEach(itms, id: \.self) { tag in
Text(tag.title ?? "")
.font(.callout)
.foregroundColor(Color(hue: 0.364, saturation: 0.939, brightness: 0.628))
.padding()
.frame(height: 24.0)
.background(Color(hue: 0.387, saturation: 0.969, brightness: 0.965, opacity: 0.207))
.frame(alignment: .center)
.cornerRadius(100)
.contextMenu {
Button {
deleteTheTag(tag)
} label: {
Label("Delete", systemImage: "trash")
}
}
}
}
}
}
我尝试了多种方法,但都失败了。
我应该如何修改我的代码?
谢谢
我用这样的关键字谷歌搜索这个问题:
SwiftUI contextMenu 不适用于子视图,而是应用于父视图
不幸的是,我没有找到我需要的东西。
我也用关键词尝试过Youbube,但我得到的较少T_T
我问了几次GPT,它确实给了我一些解决方案,我都尝试了
全部失败了T_T
以下代码对我来说工作正常(Xcode 15 beta 5)。如果问题仍然存在,您应该编辑您的问题并添加编译所需的所有代码(如何创建最小的、可重现的示例)。
struct ContentView: View {
private let tags2DList = [["123", "456", "789"], ["987", "654", "321"]]
var body: some View {
VStack(alignment: .leading) {
ForEach(tags2DList, id: \.self) { tagList in
HStack {
ForEach(tagList, id: \.self) { tag in
Text(tag)
.font(.callout)
.foregroundColor(Color(hue: 0.364, saturation: 0.939, brightness: 0.628))
.padding()
.frame(height: 24.0)
.background(Color(hue: 0.387, saturation: 0.969, brightness: 0.965, opacity: 0.207))
.frame(alignment: .center)
.contextMenu {
Button {
// some action
} label: {
Label("Delete", systemImage: "trash")
}
}
.cornerRadius(100) // <- Changed order for better animation
}
}
}
}
}
}