我有一个 macOS Monterrey 应用程序,其中包含TextField
在工具栏上。我用它来搜索我的应用程序上的文本。现在,我正在尝试添加键盘快捷键以专注于TextField
。我尝试了下面的代码,添加带有快捷方式的按钮作为测试这是否可行的方法,但我无法让它工作。这.focused()
没有做任何事情。
除此之外,我添加了一个新的菜单项Find
并将键盘快捷键设置为 cmd-L 但我不知道如何将焦点发送到 TextField。
我缺少什么?
struct AllData: View {
@FocusState private var searchFieldIsFocused: Bool
@State var searchText: String = ""
var body: some View {
NavigationView {
List(data.notes.filter { searchText.isEmpty ? true : $0.text.localizedCaseInsensitiveContains(searchText) }) {
//...
}
}
.navigationTitle("A Title")
.toolbar {
ToolbarItem(placement: .automatic) {
TextField("Search...", text: $searchText)
.textFieldStyle(RoundedBorderTextFieldStyle())
.frame(minWidth: 200)
.focused($searchFieldIsFocused)
}
//test for the focus
ToolbarItem(placement: .automatic) {
Button(action: {
print("Plus pressed")
searchFieldIsFocused = true
}) {
Image(systemName: "plus")
}
.keyboardShortcut("e", modifiers: [.command])
}
}
}
}
Yrb 评论后编辑
它似乎.focusable
不能与TextField
在工具栏上,所以他建议使用.searchable
.
尝试与.searchable
struct AllData: View {
@FocusState private var searchFieldIsFocused: Bool
@State var searchText: String = ""
var body: some View {
NavigationView {
List(data.notes.filter { searchText.isEmpty ? true : $0.text.localizedCaseInsensitiveContains(searchText) }) {
//...
}
.searchable(
text: $searchText,
placement: .toolbar,
prompt: "Search..."
)
}
.navigationTitle("A Title")
.toolbar {
//test for the focus
ToolbarItem(placement: .automatic) {
Button(action: {
print("Plus pressed")
searchFieldIsFocused = true
}) {
Image(systemName: "plus")
}
.keyboardShortcut("e", modifiers: [.command])
}
}
}
}
观察结果:
- 我无法控制搜索字段将出现在哪里,它似乎是工具栏上的最后一项,这不是我想要的,但还可以。
- 我找不到添加的方法
.focusable
这样我就可以用键盘快捷键跳转到搜索,这就是这个问题的原因
- 当您搜索时,列表会被过滤,但是当您尝试使用箭头(键盘)导航列表时,选择下一个项目后,焦点将返回到搜索字段,它不会保留在列表上,从而使导航非常方便缓慢而痛苦。
我确信我遗漏了一些东西,并且可能我的代码是错误的。有什么线索吗?
Edit #2
看来这是不可能的.searchable
:
.searchable 带有键盘快捷键的修饰符 https://developer.apple.com/forums/thread/688679