有没有办法在 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")
}
}
Run Code Online (Sandbox Code Playgroud)
而且我在 SwiftUI 中使用菜单,也不知道如何长按显示。
我的代码如下所示:
Menu() {
Button("Order Now", action: {})
Button("Adjust Order", action: {})
Button("Cancel", action: {})
} label : {
Text("HELLO")
.onLongPressGesture {
// Show menu when this triggers
}
}
Run Code Online (Sandbox Code Playgroud)
paw*_*222 11
这是一个简单的演示(为了清楚起见,menuItems在 之外提取body):
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: {})
}
}
}
Run Code Online (Sandbox Code Playgroud)
他们为 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()
}
Run Code Online (Sandbox Code Playgroud)
当用户点击或单击控件主体时将执行主要操作,而菜单呈现将在辅助手势上发生,例如长按或单击菜单指示器。
| 归档时间: |
|
| 查看次数: |
7678 次 |
| 最近记录: |