【问题标题】:How to create a UISearchBar in SwiftUI如何在 SwiftUI 中创建 UISearchBar
【发布时间】:2021-02-12 04:13:22
【问题描述】:

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

我已关注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>'

我该如何解决?

【问题讨论】:

  • 你需要绑定,但首先globalVariables是什么,throttleModel是什么?
  • 对不起,错字。我已经修好了。

标签: swift swiftui swiftui-environment


【解决方案1】:

这里是如何为观察对象发布属性传递绑定

@EnvironmentObject var globalVariables : GlobalVariables

// ... other code

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

【讨论】:

  • 看在上帝的份上。明显地!我是 SwiftUI 的新手,我的大脑无法理解它。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-27
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多