我的视图中有带keyboardShortcut的Buttons以接收keyboardShortcut,但我不希望这些Buttons可见。
我怎样才能把它们藏得最好?
我尝试这样做,但是如果我将.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)
}
}
}
2条答案
按热度按时间4ioopgfo1#
试试这个
nkoocmlb2#
我正在使用下面的View扩展将一个隐藏的底层按钮添加到View层次结构中:
这可以方便地在代码中使用,如下所示: