swiftui - 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()}
}
}
解决方案
您可以将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)
...
}
推荐阅读
- python - 使用正则表达式搜索字符串的python方式中更好的代码的建议
- mysql - 如何根据列值过滤结果
- python-3.x - 在标签中显示随机选择项目的次数
- scala - Spark 2.0 如何将 DF 日期/时间戳列转换为 scala 中的另一种日期格式?
- c# - 未找到默认语言“”的资源
- excel - 无法导入某些excel文件
- xhtml - 使用 XHTML 的 MathJax
- node.js - 在 nodejs winston logger 中为时间戳使用不同的属性名称
- database - 如何在主机上测试 postgres 数据库连接?
- android - RangeError(索引):无效值:不在 0..5 范围内,包括:6:Flutter SliverChildBuilderDelegate