简体   繁体   中英

SwiftUI Issue displaying specific number of Json Data Items

I am using SwiftUI and pulling JSON from an Online API. I have decoded the item and now struggling trying to display only 6 of the items at random. The 6 items will display once a button has been clicked but I have not created the button yet. Any Ideas on how to display 6 items at random?

import SwiftUI
import SDWebImageSwiftUI

struct TestPost: View {
    @ObservedObject var getData = ListData()
    
    var body: some View {
        NavigationView {
            VStack {
                
                // Not Working...
                // Displaying Json Data, I want to display 6 at random when view appears.
                ForEach(getData.jsonData.indices, id: \.self) { item in
                    if item < 6 {
                        ListRow(firstName: item.firstName)
                    }
                }
                
                //Working... Able to Display Names
                List(getData.jsonData) { item in
                    ListRow(firstName: item.firstName)
                }
            }
        }
    }
}

在列表中显示 JSON 项目

获取 JSON

Updated Code. I figured out how to get the 6 items and will be working on how to do it at random.

import SwiftUI
import SDWebImageSwiftUI

struct TestPost: View {
    @ObservedObject var getData = ListData()
    
    var body: some View {
        NavigationView {
            VStack {
                
                // Not Working...
                // Displaying Json Data, I want to display 6 at random when view appears.
                ForEach(getData.jsonData.indices, id: \.self) { item in
                    if item < 6 {
                        ListRow(firstName: self.getData.jsonData[item].firstName) //Updated Code...
                    }
                }
                
                //Working... Able to Display Names
                List(getData.jsonData) { item in
                    ListRow(firstName: item.firstName)
                }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM