【问题标题】:SwiftUI: ForEach filters booleanSwiftUI:ForEach 过滤器布尔值
【发布时间】:2020-02-09 15:52:26
【问题描述】:

我正在拼命地尝试使用 ForEach 来仅显示值为 true 的内容。无论我尝试什么,也会显示 false 。空气现在已经消失了,我认为这很简单,我只是看不到它。这是一段应该适用的代码:

import SwiftUI

struct txt: Identifiable {
    var id: Int
    var text: String
    var show: Bool
}

struct ContentView: View {

    @State private var array = [
        txt(id: 000, text: "True", show: true),
        txt(id: 001, text: "True", show: true),
        txt(id: 002, text: "True", show: true),
        txt(id: 003, text: "False", show: false),
        ]

    var body: some View {
        NavigationView {
            List {
                ForEach(array.indices, id: \.self) { idx in
                   Text("\(self.array[idx].text)")
                }

            }
        }
    }
}

【问题讨论】:

    标签: foreach swiftui


    【解决方案1】:

    像这样更改您的ForEach:

    ForEach(array) { arr in
         if arr.show {
             Text("\(arr.text)")
         }
    }
    

    【讨论】:

    • 啊!这就是我一直在寻找的。我的错误是愚蠢的。谢谢!
    【解决方案2】:
    List(array.filter { $0.show }){ (item) in
        Text(item.text)
    }
    

    更新:

    let ids = [0,2]
    let filteredItems = array.filter { ids.contains($0.id)}
    

    为您提供过滤后的集合,其中 仅包含两个项目,其中 Element.id == 0 或 Element.id == 2

    array.filter { $0.show } 是三个项目的集合,其中 Element.show == true

    您可以将其用作数据源

    List(array.filter { ids.contains($0.id) }){ (item) in
        Text(item.text)
    }
    

    它会为每个源集合生成一个文本

    这两个条件(或更多)都可以根据需要与任何逻辑运算符一起应用

    【讨论】:

    • 谢谢。解决方案中是否有可能额外限制 ForEach?比如只输出id:000和id:001,完全省略002再省略003?
    • 准附加范围。然而,过滤保持原样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 2013-07-13
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 2023-01-02
    • 2020-05-15
    相关资源
    最近更新 更多