我正在使用新的可搜索修饰符:https://developer.apple.com/documentation/swiftui/form/searchable(text:placement:)。当用户使用该修饰符进入视图时,该文本字段不会自动聚焦。
有没有办法让注意力集中在 上searchable?这是我的观点,它被称为NavigationLink
import SwiftUI
struct UserFindView: View {
@State private var searchText = ""
var body: some View {
Text("Please search")
.searchable(text: $searchText)
.navigationTitle("Title")
.navigationBarTitleDisplayMode(.inline)
}
}
Run Code Online (Sandbox Code Playgroud) 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
}) …Run Code Online (Sandbox Code Playgroud)