【问题标题】:Limit element in ForEach in Swift UiSwift Ui 中 ForEach 中的限制元素
【发布时间】:2019-12-06 20:03:18
【问题描述】:

我不能将我的 forEach 限制为我列表中的 3 个项目。

我尝试将它们分组或仅将列表限制为 3 项,但我没有得到我想要的结果。我有 Firestore 文档的所有条目。

import SwiftUI
import Firebase
import Ballcap

struct MainPage : View {

    @ObjectBinding var dataSource: ItemDatabase = ItemDatabase()

    var item: Item

    var body: some View {
        NavigationView {
            List {
                ForEach(self.dataSource.items.identified(by: \.id)) { item in
                                    ShortArticleItem(item: item.data!)
                                        .padding()
                                }
                VStack(alignment: .leading) {
                            Text(self.item.categorie ?? "")
                                .font(.largeTitle)
                                .fontWeight(.black)
                                .multilineTextAlignment(.leading)
                                .foregroundColor(.black)

                            ForEach( self.dataSource.items.identified(by: \.id)) { item in
                                            MediumArticleItem(item: item.data!)
                    }
                }
            }
            .navigationBarTitle(Text("The News Place"))
        }
    }

我希望 ForEach 中只有最后 3 个元素

【问题讨论】:

  • 尝试使用 suffix func 作为列表,list.suffix(3) 之类的

标签: swift xcode foreach google-cloud-firestore swiftui


【解决方案1】:

如果您使用的是数组,您可以随时使用数组函数prefix(number) 来确定要渲染的项目数


ForEach(arrayItem.prefix(5), id: \.id){ item in 
  //DO Something Here
}

【讨论】:

    【解决方案2】:

    尝试引入一个范围:

    @State var range: Range<Int> = 0..<3
    
    ForEach(range, id: \.self) { 
        ShortArticleItem(item: self.dataSource.items[$0].data!)
                                        .padding()
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-14
      • 2011-01-02
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 1970-01-01
      相关资源
      最近更新 更多