SwiftUI 按钮,在 AppKit 中扩展并接受键盘快捷键

问题描述

我需要构建这样的布局,按钮应接受键盘快捷键(AppKit):

enter image description here

Let use a button all available width in SwiftUI on MacOS AppKit 中,我找到了一个创建布局的解决方案,但这个 ExpandingButton 不接受键盘快捷键 - 可能是因为它是一个 HStack。

在上面的帖子中提出的另一个想法是给标准按钮一个 .frame(maxWidth: .infinity) 修饰符对我不起作用。

struct TEST: View {

  let columns = [
    GridItem(.flexible()),GridItem(.flexible()),GridItem(.flexible())
  ]
  let data = ["1 Text ...","2 longer Text ...","3 Text ...","4 Text/FA/Tra","5 Text ...","6 Text ...","7 Text ...","8 Text ...","9  Text ...",]

  var body: some View {
    vstack (alignment: .leading ){

      LazyVGrid(columns: columns) {
        ForEach(data.indices,id: \.self) { index in
          ExpandingButton(text:data[index],action: {print("pressed \(index)")})
          .keyboardShortcut(KeyEquivalent(Character(UnicodeScalar(0x0030+index)!)),modifiers: [.command])
        }
      }
      }
      .padding(.horizontal)
    }
    ExpandingButton(s: "Hogo"){print("hogo")}
    ExpandingButton(s: "Hogo"){print("hogo")}
    ExpandingButton(s: "Hogo"){print("hogo")}

  }
}

struct ExpandingButton: View {
  var s : String
  var action: ()->Void

  var body: some View {
    HStack (alignment: .top){
      Spacer()
      Text(s)
       .padding(4)
      Spacer()
    }
    .background(Color.gray)
    .cornerRadius(4)
    .onTapGesture  {action()}
  }
}

解决方法

您可以将 ExpandingButton 内容放入 Button,然后 keyboardShortcut 将按预期工作:

struct ExpandingButton: View {
    var s: String
    var action: () -> Void

    var body: some View {
        Button(action: action) {
            HStack(alignment: .top) {
                Spacer()
                Text(s)
                    .padding(4)
                Spacer()
            }
        }
        .background(Color.gray)
        .cornerRadius(4)
    }
}

或者,您可以删除 ExpandingButton 并使用标准 Button

VStack(alignment: .leading) {
    LazyVGrid(columns: columns) {
        ForEach(data.indices,id: \.self) { index in
            Button(action: { print("pressed \(index)") }) {
                Text(data[index])
            }
            .keyboardShortcut(KeyEquivalent(Character(UnicodeScalar(0x0030 + index)!)),modifiers: [.command])
            .frame(maxWidth: .infinity)
        }
    }
    .padding(.horizontal)
    ...
}