![](/img/trans.png)
[英]Qt: Are keyboard shortcut assignments (using “&”) in Qt apps not working for Mac OSX?
[英]Focus on a TextField using a keyboard shortcut
我有一個 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
的方法,因此我可以使用鍵盤快捷鍵跳轉到搜索,這就是這個問題的原因我確定我遺漏了什么,可能我的代碼有誤。 有什么線索嗎?
編輯 #2
.searchable
似乎是不可能的:
我最終使用.searchable()
修飾符(僅在macOS
macOS 12.3
上測試)在 macOS 上運行以下內容:
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)
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.