我想在swiftUI中从indexvariable开始的循环中设置一个键盘快捷键。
我的代码(注释行)无法编译。
var body: some View {
ForEach (1...5, id: \.self) { index in
Button("\(index)"){print("\(index) pressed")}
//.keyboardShortcut("\(index)", modifiers: [.command])
}
}
}这是怎么做到的呢?
发布于 2021-01-05 17:35:50
@Yrb的解决方案可以编译,但不能像预期的那样工作,因为UnicodeScalar(索引)被解释为带有数字索引的unicode。
这对我很有效:
struct BList: View {
var body: some View {
VStack{
ForEach (1...5, id: \.self) { index in
Button("\(index)"){print("\(index) pressed")}
.keyboardShortcut(KeyEquivalent(Character(UnicodeScalar(0x0030+index)!)) , modifiers: [.command])
}
}
}
}发布于 2021-01-05 09:48:18
您需要将索引从Int转换为字符,然后再转换为KeyEquivalent。我强制解开了UnicodeScalar,因为它返回一个可选的,但对于这个例子,我们保证有一个Int,这应该不是问题。但要知道它就在那里。
var body: some View {
ForEach (1...5, id: \.self) { index in
Button("\(index)"){print("\(index) pressed")}
.keyboardShortcut(KeyEquivalent(Character(UnicodeScalar(index)!)), modifiers: [.command])
}
}https://stackoverflow.com/questions/65571683
复制相似问题