让我解释一下,我有一个带有 SearchBarView 的父视图,我正在传递这样的焦点状态绑定。
SearchBarView(searchText:$object.searchQuery, searching: $object.searching, focused: _searchIsFocused
这非常有效,因为
@FocusState var searchIsFocused: Bool
是在父视图中定义的,并将其传递给 SearchBarView (子视图)。在父级中,我可以检查值的变化,一切正常。
问题在于当在父级中我在
.toolbar {}
和 ToolBarItem()
中有 SearchBarView 时。什么也没有发生,焦点的值没有改变,等等。我的 SearchBarView 在顶部导航栏中,但仍然想在那里使用它..但我需要能够知道它何时处于焦点状态。如果我在任何 VStack 或其他东西中使用,一切都很完美..
-- 编辑-- 提供更多代码来测试
搜索栏视图
struct SearchBarView: View {
@Environment(\.colorScheme) var colorScheme
@Binding var searchText: String
@Binding var searching: Bool
@FocusState var focused: Bool
var body: some View {
ZStack {
Rectangle()
.foregroundColor(colorScheme == .dark ? Color("darkSearchColor") : Color.white)
.overlay(
RoundedRectangle(cornerRadius: 13)
.stroke(.black.opacity(0.25), lineWidth: 1)
)
HStack {
Image(systemName: "magnifyingglass").foregroundColor( colorScheme == .dark ? .gray : .gray )
TextField("Search..", text: $searchText )
.focused($focused, equals: true)
.padding(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 20))
.disableAutocorrection(true).onSubmit {
let _ = print("Search textfield Submited by return button")
}
}
.foregroundColor(colorScheme == .dark ? Color("defaultGray") :.gray)
.padding(.leading, 13)
.padding(.trailing, 20).overlay(
HStack {
Spacer()
if searching {
ActivityIndicator().frame(width:15,height:15).aspectRatio(contentMode: .fit).padding(.trailing,15)
}
}
)
.onChange(of: focused) { searchIsFocused in
let _ = print("SEARCH IS FOCUSED VALUE: \(searchIsFocused) ")
}
}
.frame(height: 36)
.cornerRadius(13)
}
}
-- 首页查看代码--
struct HomeView: View {
@Environment(\.colorScheme) var colorScheme
@FocusState var searchIsFocused: Bool
@State var searching:Bool = false
@State var searchQuery: String = ""
var body: some View {
NavigationStack {
GeometryReader { geofull in
ZStack(alignment: .bottom) {
Color("background")//.edgesIgnoringSafeArea([.all])
ScrollView(showsIndicators: false) {
VStack {
// Testing Bar inside VStack.. Here It Works. comment the bar the leave
// the one inside the .toolbar ToolbarItem to test
SearchBarView(searchText:$searchQuery, searching: $searching, focused: _searchIsFocused).padding(0)
}.toolbar {
//MARK: Navbar search field
ToolbarItem(placement:.principal) {
SearchBarView(searchText:$searchQuery, searching: $searching, focused: _searchIsFocused).padding(0)
}
}
.onChange(of: searchIsFocused) { searchIsFocused in
let _ = print("HOME VIEW searchIsFocused VALUE: \(searchIsFocused) ")
}
}
}
}
}
}
}
将视图修改器
focusSection()
添加到您的 SearchBarView
SearchBarView(searchText:$searchQuery, searching: $searching, focused: _searchIsFocused)
.focusSection()
.padding(0)
自 macOS 13
起可用