我已经实现了一个简单的UISearchBar,但是,当我直接调用搜索栏时,“ X”按钮才起作用。为什么会这样?
这是我的代码:
UISearchBar
struct SearchBarView: View, UIViewRepresentable {
@Binding var text: String
class Coordinator: NSObject, UISearchBarDelegate {
@Binding var text: String
init(text: Binding<String>) {
_text = text
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
text = searchText
}
}
func makeCoordinator() -> SearchBarView.Coordinator {
return Coordinator(text: $text)
}
func makeUIView(context: UIViewRepresentableContext<SearchBarView>) -> UISearchBar {
let searchBar = UISearchBar(frame: .zero)
searchBar.delegate = context.coordinator
searchBar.autocapitalizationType = .none
searchBar.enablesReturnKeyAutomatically = true
searchBar.showsSearchResultsButton = true
searchBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
searchBar.searchTextField.backgroundColor = UIColor.init(red: 239/255, green: 239/255, blue: 239/255, alpha: 1)
searchBar.isTranslucent = true
searchBar.placeholder = "Pesquisar"
return searchBar
}
func updateUIView(_ uiView: UISearchBar, context: UIViewRepresentableContext<SearchBarView>) {
uiView.text = text
}
}
我的TopBarView在另一个文件中
struct TopBarView: View {
@EnvironmentObject var environmentController : EnvironmentController
var body: some View {
HStack() {
Button(action: {
self.environmentController.environment.showMenu.toggle()
}) {
Image(systemName: "line.horizontal.3")
.background(
RoundedRectangle(cornerRadius: 8.0)
.foregroundColor(Color.init(red: 239/255, green: 239/255, blue: 239/255))
.frame(width: 36, height: 36, alignment: .center))
.foregroundColor(.black)
.imageScale(.large)
.font(.subheadline)
.frame(width: 40, height: 40, alignment: .center)
}
SearchBarView(text: self.$environmentController.environment.searchText)
}
.padding(.top, 30)
.padding(.all)
}
}
我的MainView,也在另一个文件中
struct NextDeparturesView: View {
@ObservedObject var userSettingsController = UserSettingsController()
@EnvironmentObject var environmentController : EnvironmentController
@State private var showMap = false
var body: some View {
VStack() {
//If showUserActionSheet is false or showMap is true, display the menu button, the search bar and the map
if(!self.userSettingsController.showUserCityActionSheet || showMap) {
MapView()
.overlay(
TopBarView(),
alignment: .top)
.edgesIgnoringSafeArea(.top)
.onTapGesture {
if(self.environmentController.environment.showMenu) {
self.environmentController.environment.showMenu.toggle()
}
}
}
}
因此,如果在我的MainView中直接调用SearchBarView,则“ x”按钮将起作用。但是,如果使用代码中的TopBarView,则“ x”按钮将停止工作。值得一提的是,在搜索栏中进行书写总是可以的,只是“ x”按钮停止起作用。
我是新手,我想念什么?
谢谢
编辑
我仍然无法弄清楚,但是我猜想它在覆盖层内时会停止工作。在我的MainView中,如果我将TopBarView()调用移到叠加层之外,那么它将起作用。
EDIT2
因此,如果我在我的MainView叠加层中添加allowHitTesting(false),则UISearchBar将开始工作,但是,菜单按钮会停止...如果叠加层中只有一个动作,那么这可能是您的解决方案。
好吧,所以如果有人发现自己和我处于同一位置并且找不到解决方案,那么让我工作的唯一方法就是放弃覆盖并使用ZStack开发更复杂的视图。
在问题编辑中,您可以看到我之前尝试过的内容,也许会对您有所帮助。
但是,如果有人最终想出一个更好的解决方案,我将对其进行更改。