Home > other >  Hide a button in SwiftUI to use its keyboardShortcut on MacOS
Hide a button in SwiftUI to use its keyboardShortcut on MacOS

Time:01-19

I have Buttons with a keyboardShortcut in my view to receive keyboardShortcuts, but I don't want the Buttons to be visible.
Ho do I hide them best?
I tried like this, but if I add .buttonStyle(PlainButtonStyle()) to the group, the buttons with the arrows don't work anymore (default and escape do).

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)
    }
  }
}

CodePudding user response:

Try this

  Group{
    Button(""){dismiss()}.keyboardShortcut(.cancelAction)
    Button(""){dismiss()}.keyboardShortcut(.defaultAction)
    Button(""){left()}.keyboardShortcut(.leftArrow)
    Button(""){right()}.keyboardShortcut(.rightArrow)
  }
  .opacity(0)     // << here !!
  •  Tags:  
  • Related