如何在SwiftUI中创建一个UISearchBar

3

我正在尝试为了学习目的,创建自己的SwiftUI版本的UISearchBar

我已经按照这篇教程中的步骤操作,并且此时我的搜索栏结构如下所示:

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>'

我该如何解决这个问题?


你需要绑定,但首先 globalVariables 和其中的 throttleModel 是什么? - Asperi
抱歉,打错了。我已经修正了。 - Duck
1个回答

4

以下是如何将绑定传递给观察对象的发布属性

@EnvironmentObject var globalVariables : GlobalVariables

// ... other code

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

1
拜托了,显然!我是SwiftUI的新手,我的大脑无法理解它。谢谢。 - Duck

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接