首页 > 解决方案 > SwiftUI Button,在 AppKit 中扩展并接受键盘快捷键

问题描述

我需要构建这样的布局,并且按钮应接受键盘快捷键(AppKit): 在此处输入图像描述

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

标签: swiftuikeyboard-shortcutsappkit

解决方案


您可以将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)
    ...
}

推荐阅读