如何在SwiftUI中手动显示contextMenu?

时间:2019-09-25 16:26:32

标签: swiftui

我想通过单击鼠标左键显示contextMenu吗? 如何在SwiftUI中手动显示视图?

Image(systemName: "book")
.contextMenu {
   Text("something1")
   Text("something2")
   Text("something3")
}

2 个答案:

答案 0 :(得分:1)

您可以将MenuButtonmenuButtonStyle一起使用来创建一个按钮,单击该按钮将显示一个菜单。似乎目前仅是Mac。

MenuButton("Menu") {
    Button(action: {
      print("Clicked an item")
    }) {
        Text("Menu Item Text")                
    }
}.menuButtonStyle(BorderlessButtonMenuButtonStyle())

答案 1 :(得分:1)

当前接受的答案使用MenuButton,现已弃用。以下是如何使用新的Menu选项。

现在可以通过Menu(iOS 14 +,MacOS 11+)来实现
WWDC video的〜11:15涵盖了菜单。

游乐场示例:

import SwiftUI
import PlaygroundSupport

struct ContentView: View {
    
    var body: some View {
        HStack {
            // Other views
            Text("Example View 1")

            // Button, that when tapped shows 3 options
            Menu {
                Button(action: {
                    
                }) {
                    Label("Add", systemImage: "plus.circle")
                }
                Button(action: {
                    
                }) {
                    Label("Delete", systemImage: "minus.circle")
                }
                Button(action: {
                    
                }) {
                    Label("Edit", systemImage: "pencil.circle")
                }
            } label: {
                Image(systemName: "ellipsis.circle")
            }
        }
        .frame(width: 300, height: 300, alignment: .center)
    }
}

PlaygroundPage.current.setLiveView(ContentView())

如果您希望支持MacOS 10.15,则可以执行以下操作:

if #available(iOS 14, macOS 11, *) {
    Menu {
        Button(action: {
            
        }) {
            Label("Add", systemImage: "plus.circle")
        }
        Button(action: {
            
        }) {
            Label("Delete", systemImage: "minus.circle")
        }
        Button(action: {
            
        }) {
            Label("Edit", systemImage: "pencil.circle")
        }
    } label: {
        Image(systemName: "ellipsis.circle")
    }
} else if #available(macOS 10.15, *) {
    MenuButton(
        label: Image(nsImage: NSImage(named: NSImage.actionTemplateName)!),
        content: {
            Button(action: {}) {
                HStack {
                    Image(nsImage: NSImage(named: NSImage.addTemplateName)!)
                    Text("Add")
                }
            }
            Button(action: {}) {
                HStack {
                    Image(nsImage: NSImage(named: NSImage.removeTemplateName)!)
                    Text("Delete")
                }
            }
            Button(action: {}) {
                HStack {
                    Image(nsImage: NSImage(named: NSImage.refreshTemplateName)!)
                    Text("Edit")
                }
            }
        })
        .menuButtonStyle(BorderlessButtonMenuButtonStyle())
} else {
    // Custom code here would be needed to support iOS 13 and MacOS 10.14
}