首页 > 解决方案 > SwiftUi 水平滚动视图,带有来自 Api 的数据

问题描述

我需要使用从 api 加载的数据制作一个水平滚动视图。我有这样的看法:

 ScrollView(.horizontal,showsIndicators:false) {

      HStack(spacing: 20) {
        ForEach(self.images, id: \.self) { item in

                URLImage(URL(string:item)!)
                               { proxy in
                                   proxy.image
                                       .resizable()
                               }.frame(width: UIScreen.main.bounds.width - 120, height: 200).aspectRatio(contentMode: .fit)
                               .cornerRadius(15)
                               .opacity(0.7)


    }

    }.onAppear(perform: loadData)

}.padding(.all,20)

当我删除滚动视图时,数据正在完美加载。对此有什么建议吗?谢谢

标签: iosswiftswiftuiscrollviewswiftui-list

解决方案


试试这个:

这是一个快速而肮脏的例子......;)

var imageLoader = ImageLoader()

class ImageLoader {

    var images : [Image] = []

    init() {
        loadData()
    }

    func loadData() {

        for _ in 0..<10 {
            images.append( Image(systemName: "circle.fill"))
        }
    }
}

struct ContentView: View {

       var body: some View {

        ScrollView(.horizontal,showsIndicators:false) {

        HStack(spacing: 20) {

                ForEach(0..<imageLoader.images.count, id: \.self) { item in

                    imageLoader.images[item]
                        .resizable()
                        .frame(width: UIScreen.main.bounds.width - 120, height: 200).aspectRatio(contentMode: .fit)
                        .cornerRadius(15)
                        .opacity(0.7)
                }
            }.background(Color.yellow)
        }.background(Color.orange)
    }
}

推荐阅读