gpt4 book ai didi

swift - 如何在 SwiftUI 中创建 UISearchBar

转载 作者:行者123 更新时间:2023-12-04 01:12:00 25 4
gpt4 key购买 nike

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

因为搜索文本的值必须传播到其他界面元素,这将对更改使用react。

但随后我在 SearchBarUI 行上出现此错误,指向 globalVariables.searchText:

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

我该如何解决?

最佳答案

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

@EnvironmentObject var globalVariables : GlobalVariables

// ... other code

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

关于swift - 如何在 SwiftUI 中创建 UISearchBar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64595842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com