【问题标题】:SwiftUI Button, that expands and accepts keyboard-shortcuts in AppKitSwiftUI 按钮,在 AppKit 中扩展并接受键盘快捷键
【发布时间】:2021-01-05 10:24:35
【问题描述】:

我需要构建这样的布局,并且按钮应接受键盘快捷键(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()}
  }
}

【问题讨论】:

    标签: swiftui keyboard-shortcuts appkit


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-12-12
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多