我的视图中有带键盘快捷方式的按钮来接收键盘快捷方式,但我不希望按钮可见
我怎样才能最好地隐藏它们
我试过这样做,但如果我将.buttonStyle(PlainButtonStyle())
添加到组中,带有箭头的按钮将不再工作(默认和转义(。
import SwiftUI
struct HiddenCommandbutton: View {
@State var showMiniDialog = false
var body: some View {
VStack{
Text("Hello, world!")
.padding()
Button("show"){showMiniDialog = true}
.sheet(isPresented: $showMiniDialog){
MiniDialog()
}
}
}
}
struct MiniDialog: View {
@Environment(.dismiss) var dismiss
@State var sel: Int?
var options = ["Opt1", "Opt2", "Opt3", "Opt4"]
var rEdge:Int { options.count-1}
var body: some View {
ZStack{
Group{
Button(""){dismiss()}.keyboardShortcut(.cancelAction)
Button(""){dismiss()}.keyboardShortcut(.defaultAction)
Button(""){left()}.keyboardShortcut(.leftArrow)
Button(""){right()}.keyboardShortcut(.rightArrow)
}//.buttonStyle(PlainButtonStyle())
.padding(0)
HStack{
ForEach(options.indices) { index in
option(options[index],pos: index)
}
}
}
.padding(4)
}
func left(){
if sel == nil {
sel = rEdge
} else if sel! > 0 {
sel = sel! - 1
}
}
func right(){
if sel == nil {
sel = rEdge
} else if sel! < rEdge {
sel = sel! + 1
}
}
@ViewBuilder func option(_ title: String, pos: Int) -> some View {
if (sel != nil && sel! == pos) {
Text(title)
.padding(4)
.background(Color.red)
.cornerRadius(5.0)
} else {
Text(title)
.padding(4)
.cornerRadius(5.0)
}
}
}
试试这个
Group{
Button(""){dismiss()}.keyboardShortcut(.cancelAction)
Button(""){dismiss()}.keyboardShortcut(.defaultAction)
Button(""){left()}.keyboardShortcut(.leftArrow)
Button(""){right()}.keyboardShortcut(.rightArrow)
}
.opacity(0) // << here !!
我正在使用以下View扩展向View层次结构添加一个隐藏的底层按钮:
extension View {
/// Adds an underlying hidden button with a performing action that is triggered on pressed shortcut
/// - Parameters:
/// - key: Key equivalents consist of a letter, punctuation, or function key that can be combined with an optional set of modifier keys to specify a keyboard shortcut.
/// - modifiers: A set of key modifiers that you can add to a gesture.
/// - perform: Action to perform when the shortcut is pressed
public func onKeyboardShortcut(key: KeyEquivalent, modifiers: EventModifiers = .command, perform: @escaping () -> ()) -> some View {
ZStack {
Button("") {
perform()
}
.hidden()
.keyboardShortcut(key, modifiers: modifiers)
self
}
}
}
这可以在你的代码中方便地使用,如下所示:
NavigationView()
// on cmd+W
.onKeyboardShortcut(key: "w", modifiers: .command) {
// hide the app
MainPanelController.shared.windowShouldClose()
}