如何在SwiftUI列表行中的按钮上应用上下文菜单?

10
当我长按列表行中的一个按钮时,所有按钮的上下文菜单都会显示出来。看起来好像整个列表行都被选中了。我该如何做才能仅为所按下的按钮显示上下文菜单?
我看到了这个问题,它有一定的相关性,并尝试使用BorderlessButtonStyle()。它使得行中的各个按钮可点击,但无法解决上下文菜单问题。我也尝试使用.onTapGesture()而不是Button(),但也没有成功。
在下面的示例中,我期望只在按下按钮1时看到“按钮1的操作”,但是“按钮2的操作”也会显示出来。

enter image description here

struct ContentView: View {
    var body: some View {
        List {
            ForEach((1..<3), content: { _ in
                ListButton()
            })
        }
    }
}

struct ListButton: View {
    var body: some View {
        HStack {
            Spacer()

            Button("Button 1") { }
                .buttonStyle(BorderlessButtonStyle())
                .contextMenu(menuItems: {
                    Text("Action for button 1")
                })

            Spacer()

            Button("Button 2") { }
                .buttonStyle(BorderlessButtonStyle())
                .contextMenu(menuItems: {
                    Text("Action for button 2")
                })

            Spacer()
        }
    }
}

使用ScrollView而不是List来限制上下文菜单只在行的某些部分中出现。 - Arman
@Arman 这解决了特定的问题,但同时也失去了所有列表功能,比如滑动删除和重新排序(这也是我需要的)。 - Benjamin Angeria
@BenjaminAngeria 这个有更新了吗? - George
1
@George_E 很抱歉,不是这样的... - Benjamin Angeria
2个回答

3

你可以使用Menu替代ContextMenu,并使用菜单的标签来显示你的按钮;作为替代方案。

不过,为了让按钮手势比行本身更具优先级,您可以在按钮末尾添加.highPriorityGesture(TapGesture())

你可以这样使用Menu来实现你想要的效果:

struct ListButton: View {
    var body: some View {
        HStack {
            Spacer()

            Button("Button 1") { }
                .buttonStyle(BorderlessButtonStyle())
                .contextMenu(menuItems: {
                    Text("Action for button 1")
                })

            Spacer()
            // Here I used menu instead of the button 2
            Menu {
                Text("Action for button 2")
            } label: {
                Button("Button 2") { }
                    .buttonStyle(BorderlessButtonStyle())

            }.highPriorityGesture(TapGesture())

            Spacer()
        }
    }
}

0
只需切换到修复问题的ScrollView即可!

如果你看一下问题的评论,那么这个方法是被建议过的。然而,这意味着你会失去默认列表功能,比如“滑动删除”和重新排序。不过最终我还是采用了这种方法... - Benjamin Angeria
如果你问我,这是一个bug,而且苹果肯定不会修复它!切换到滚动视图并使用自定义的滑动操作。 - Hamed Hosseini

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接