TextField我有一个 macOS Monterrey 应用程序,工具栏上有。我用它来搜索我的应用程序上的文本。现在,我正在尝试添加键盘快捷键以专注于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])
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
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])
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
观察结果:
.focusable这样我就可以使用键盘快捷键跳转到搜索,这就是这个问题的原因我确信我遗漏了一些东西,并且可能我的代码是错误的。有什么线索吗?
编辑#2
看来这是不可能的.searchable:
小智 3
我最终得到了以下内容来使用macOS修饰符.searchable()(仅在 上进行了测试macOS 12.3):
import SwiftUI
@main
struct MyApp: App {
@State var searchText = ""
var items = ["Item 1", "Item 2", "Item 3"]
var searchResults: [String] {
if searchText.isEmpty {
return items
} else {
return items.filter { $0.contains(searchText) }
}
}
var body: some Scene {
WindowGroup {
List(self.searchResults, id: \.self) { item in
Text(item)
}.searchable(text: self.$searchText)
}.commands {
CommandMenu("Find") {
Button("Find") {
if let toolbar = NSApp.keyWindow?.toolbar,
let search = toolbar.items.first(where: { $0.itemIdentifier.rawValue == "com.apple.SwiftUI.search" }) as? NSSearchToolbarItem {
search.beginSearchInteraction()
}
}.keyboardShortcut("f", modifiers: .command)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
853 次 |
| 最近记录: |