I am trying to create my own SwiftUI version of a UISearchBar
, for learning purposes.
I have followed this tutorial
and at this point my search bar struct is like this:
import Foundation
import SwiftUI
struct SearchBarUI: View {
@Binding var searchText:String
var textColor:Color
var boxColor:Color
var boxHeight:CGFloat
public init(_ text:Binding<String>, textColor:Color, boxColor:Color, boxHeight:CGFloat) {
self._searchText = text
self.textColor = textColor
self.boxColor = boxColor
self.boxHeight = boxHeight
}
var body: some View {
HStack {
Image(systemName: "magnifyingglass")
.padding(.leading, -10)
.foregroundColor(.secondary)
TextField("Search", text: $searchText, onCommit: {
UIApplication.shared.windows.first { $0.isKeyWindow }?.endEditing(true)
})
.padding(.leading, 10)
Button(action: {
self.searchText = ""
}) {
Image(systemName: "xmark.circle.fill")
.foregroundColor(.secondary)
.opacity(searchText == "" ? 0 : 1)
.animation(.linear)
}
}.padding(.horizontal)
}
}
But here is the problem.
When I use this searchbar at ContentView, I want the search text variable to be like this:
class GlobalVariables: ObservableObject {
@Published var searchText:String = ""
}
@EnvironmentObject var globalVariables : GlobalVariables
SearchBarUI(globalVariables.searchText,
textColor:.black,
boxColor:.gray,
boxHeight:50)
because the value of the search text must propagate to other interface elements, that will react to the change.
But then I have this error on the SearchBarUI
line, pointing to globalVariables.searchText
:
Cannot convert value of type 'String' to expected argument type 'Binding<String>'
How do I solve that?