问题描述
我的应用中有一个 SwiftUI Text
视图,我想在我点击它时显示 UIMenuController 或其等效的 SwiftUI。我可以通过向我的视图添加 onTapGesture
块来成功捕获点击操作,但我找不到任何显示如何显示菜单的示例。是否有等效于 UIMenuController
的 SwiftUI?我需要为它创建整个 UIViewRepresentable 吗?
解决方法
如果您想要点击显示的菜单,则有 Menu
:
import SwiftUI
struct ContentView: View {
@State private var selection = "?"
var body: some View {
VStack {
Menu(
content: {
Button("♥️ - Hearts") {
selection = "♥️"
}
Button("♣️ - Clubs") {
selection = "♣️"
}
Button("♠️ - Spades") {
selection = "♠️"
}
Button("♦️ - Diamonds") {
selection = "♦️"
}
},label: {
Text("Favorite Card Suit: \(self.selection)")
}
)
}
}
}
,
SwiftUI 中有一个 contextMenu
辅助视图
struct ContentView: View {
@State private var fave = "?"
var body: some View {
VStack {
Text("Favorite Card Suit")
.padding()
.contextMenu {
Button("♥️ - Hearts",action: selectHearts)
Button("♣️ - Clubs",action: selectClubs)
Button("♠️ - Spades",action: selectSpades)
Button("♦️ - Diamonds",action: selectDiamonds)
}
Text("Your favourite is")
Text(fave)
}
}
func selectHearts() {
fave = "♥️"
}
func selectClubs() {
fave = "♣️"
}
func selectSpades() {
fave = "♠️"
}
func selectDiamonds() {
fave = "♦️"
}
}
您甚至不必听水龙头,只需长按即可调出菜单。