过滤可识别对象中包含的字符串变量的元素

问题描述 投票:0回答:1

我正在为 macOS 编写一个 Swift 应用程序。 我是 Swift 的初学者,所以我的问题对你来说可能看起来很愚蠢,对此我深表歉意......

我有一个包含以下两个字符串变量的可识别变量:

struct ShortcutInfo: Identifiable {
    let id: String
    let name: String
}

我最常用的变量是“name”,包含文本列表。

我尝试使用 TextField 过滤列表。过滤后的列表应出现在选取器中。

@State var filteredShortcuts = ShortcutInfo(id: "", name: "").name.filter($0.lowercased().contains(searchText.lowercased()))

TextField("", text: $searchText)
                        
Picker("", selection: $selection) {
    ForEach(filteredShortcuts) { item in
        Text(item)
    }
}

但是我收到错误“无法在属性初始值设定项中使用实例成员“searchText”;属性初始值设定项在“self”可用之前运行”。 我的代码有什么问题吗?

此外,我不确定我的代码在选择器中显示列表的有效性。

提前致谢。

swift string macos filter identifiable
1个回答
0
投票

您无法过滤顶层的文本,您必须过滤文本,例如在

onChange
修饰符中

struct ContentView: View {
    @State private var shortcuts = [ShortcutInfo(id: "001", name: "George"), ShortcutInfo(id: "002", name: "Nancy")]
    @State private var filteredShortcuts = [ShortcutInfo]()
    @State private var selection = ShortcutInfo(id: "+++None", name: "None")
    @State private var searchText = ""
    
    var body: some View {
        VStack {
            TextField("Test", text: $searchText)
            
            Picker("", selection: $selection) {
                Text("None")
                    .tag("+++None")
                ForEach(filteredShortcuts) { item in
                    Text(item.name)
                }
            }
            .onChange(of: searchText) { _, newValue in
                filteredShortcuts = shortcuts.filter{$0.name.localizedStandardContains(searchText)}
            }
        }
    }
}

注意:

ShortcutInfo
必须符合
Hashable

© www.soinside.com 2019 - 2024. All rights reserved.