如何在SwiftUI中创建UISearchBar

问题描述

出于学习目的,我正在尝试创建自己的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 { $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)
  }
}

但这是问题所在。

当我在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 !!