SwiftUI的ForEach仅返回数组中的第一个值

ygya80vv  于 2023-02-21  发布在  Swift
关注(0)|答案(1)|浏览(132)

当我在数组中进行搜索时,我只得到第一个结果,而不是我搜索的结果。例如,在searchingText.isEmpty部分中有“John”和“玛丽”。当我搜索Mary时,我得到John。当我再次搜索John时,我得到John,这是数组中的第一个名字。我应该在代码中更改什么吗?

struct LikeInfo: View {
    @ObservedObject var viewModel: PostViewModel
    @State private var searchingText = ""

    var searchResults: [String] {
        return viewModel.announcement.likedName.filter { $0.contains(searchingText) }
        }
    
    var body: some View {
        ScrollView{
            if searchingText.isEmpty {
                ForEach(0..<(viewModel.announcement.liked.count), id: \.self) { i in
                    HStack {
                         Text(viewModel.announcement.likedName[i]
                        Spacer()
                    }
                }
            } else {
                 ForEach(0..<(searchResults.count), id: \.self) { i in                    VStack {
                        HStack {
                            Text(searchResults[i]
                            Spacer()
                        }
                       
                    }
                }
            }
        }
    }
}
hmae6n7t

hmae6n7t1#

ForEach是使用声明性编程范例的View,而不是命令性for循环。如果尝试执行以下操作:
0..<(viewModel.announcement.liked.count)

id: \.self

viewModel.announcement.likedName[i]
它会崩溃的。
我建议看看docs for ForEach来学习如何使用它,例如。

private struct NamedFont: Identifiable {
    let name: String
    let font: Font
    var id: String { name }
}

private let namedFonts: [NamedFont] = [
    NamedFont(name: "Large Title", font: .largeTitle),
    NamedFont(name: "Title", font: .title),
    NamedFont(name: "Headline", font: .headline),
    NamedFont(name: "Body", font: .body),
    NamedFont(name: "Caption", font: .caption)
]

var body: some View {
    ForEach(namedFonts) { namedFont in
        Text(namedFont.name)
            .font(namedFont.font)
    }
}

相关问题