如何在SwiftUI中通过长按手势打开菜单

3

在SwiftUI中,有没有一种方法可以通过长按手势显示上下文菜单?

我有这样的一个代码:

Text(messageModel.message)
  .padding(.vertical,8)
  .padding(.horizontal,12)
  .background(Constants.clientMessageColor)
  .foregroundColor(Color.black)
  .cornerRadius(20, corners: [.topLeft,.bottomLeft,.topRight, .bottomRight])
  .onTapGesture {
       self.isExpanded.toggle()
       self.isClientNameVisible.toggle()
  }
  .contextMenu {
       Button(action: {
                                        
       }) {
             Text("Normal Colors")
             Image(systemName: "paintbrush")
       }
   }

还有我在SwiftUI中使用Menu,但不知道如何在长按时显示。

我的代码看起来像这样:

Menu() {
    Button("Order Now", action: {})
    Button("Adjust Order", action: {})
    Button("Cancel", action: {})
} label : {
    Text("HELLO")
        .onLongPressGesture {
            // Show menu when this triggers
        }
}
2个回答

11
这里有一个简单的演示(为了清晰起见,menuItemsbody之外提取):
struct ContentView: View {
    var body: some View {
        VStack {
            Text("On long press")
                .contextMenu {
                    menuItems
                }
            Menu("On tap") {
                menuItems
            }
        }
    }
    
    var menuItems: some View {
        Group {
            Button("Action 1", action: {})
            Button("Action 2", action: {})
            Button("Action 3", action: {})
        }
    }
}

3
他们为iOS 15+添加了primaryAction调用。
以下是文档中的示例代码。
Menu {
    Button(action: addCurrentTabToReadingList) {
        Label("Add to Reading List", systemImage: "eyeglasses")
    }
    Button(action: bookmarkAll) {
        Label("Add Bookmarks for All Tabs", systemImage: "book")
    }
    Button(action: show) {
        Label("Show All Bookmarks", systemImage: "books.vertical")
    }
} label: {
    Label("Add Bookmark", systemImage: "book")
} primaryAction: {
    addBookmark()
}

当用户点击或触摸控件主体时,将执行主要操作,而菜单的呈现则需要进行第二次手势操作,例如长按或点击菜单指示器。


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