如何在 SwiftUI 中创建 UISearchBar

How to create a UISearchBar in SwiftUI

出于学习目的,我正在尝试创建自己的 UISearchBar SwiftUI 版本。

我关注了this tutorial

此时我的搜索栏结构是这样的:

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 { [=10=].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)
  }
}

但问题来了。

当我在 ContentView 中使用此搜索栏时,我希望搜索文本变量如下所示:

class GlobalVariables: ObservableObject {
  @Published var searchText:String = ""
}

@EnvironmentObject var globalVariables : GlobalVariables

SearchBarUI(globalVariables.searchText,
            textColor:.black,
            boxColor:.gray,
            boxHeight:50)

因为搜索文本的值必须传播到其他界面元素,这将对更改做出反应。

但是我在 SearchBarUI 行上有这个错误,指向 globalVariables.searchText:

Cannot convert value of type 'String' to expected argument type 'Binding<String>'

我该如何解决?

下面是如何为已发布的观察对象传递绑定属性

@EnvironmentObject var globalVariables : GlobalVariables

// ... other code

SearchBarUI($globalVariables.searchText,     // << here !!