3

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?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Duck
  • 34,902
  • 47
  • 248
  • 470

1 Answers1

4

Here is how to pass binding for observed object published property

@EnvironmentObject var globalVariables : GlobalVariables

// ... other code

SearchBarUI($globalVariables.searchText,     // << here !!
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • 1
    For heaven's sake. obviously! I am new to SwiftUI and my brain is failing to wrap around it. Thanks – Duck Oct 29 '20 at 17:10