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?

2
  • You need binding, but at first what is globalVariables and what is throttleModel in it? Commented Oct 29, 2020 at 17:03
  • sorry, typo. I have fixed. Commented Oct 29, 2020 at 17:05

1 Answer 1

4

Here is how to pass binding for observed object published property

@EnvironmentObject var globalVariables : GlobalVariables

// ... other code

SearchBarUI($globalVariables.searchText,     // << here !!
Sign up to request clarification or add additional context in comments.

1 Comment

For heaven's sake. obviously! I am new to SwiftUI and my brain is failing to wrap around it. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.