使用 SwiftUI 加载更多功能 [英] Load more functionality using SwiftUI

查看:21
本文介绍了使用 SwiftUI 加载更多功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经将 ScrollView 与 HStack 一起使用,现在我需要在用户最终滚动时加载更多数据.

i have used ScrollView with HStack, now i need to load more data when user reached scrolling at last.

var items: [Landmark]

我使用 ForEach

ScrollView(showsHorizontalIndicator: false) {
    HStack(alignment: .top, spacing: 0) {
        ForEach(self.items) { landmark in
            CategoryItem(landmark: landmark)
        }
    }
}

SwiftUI 中管理更多加载而不使用自定义操作(如加载更多按钮)的最佳解决方案是什么.

What is the best possible solution to manage load more in SwiftUI without using custom action like loadmore button.

推荐答案

为此目的最好使用 ForEach 和 List

It's better to use ForEach and List for this purpose

struct ContentView : View {
    @State var textfieldText: String = "String "
    private let chunkSize = 10
    @State var range: Range<Int> = 0..<1

    var body: some View {
        List {
            ForEach(range) { number in
                Text("\(self.textfieldText) \(number)")
            }
            Button(action: loadMore) {
                Text("Load more")
            }
        }
    }

    func loadMore() {
        print("Load more...")
        self.range = 0..<self.range.upperBound + self.chunkSize
    }
}

在这个例子中,你每次按下加载更多它会增加状态属性的范围.您可以为 BindableObject 做同样的事情.如果您想自动执行此操作,您可能应该阅读 PullDownButton(我不确定它是否适用于 PullUp)

In this example each time you press load more it increases range of State property. The same you can do for BindableObject. If you want to do it automatically probably you should read about PullDownButton(I'm not sure if it works for PullUp)

UPD:作为一个选项,您可以通过在最后一个单元格上使用 onAppear 修饰符来下载新项目(在本例中它是一个静态按钮)

UPD: As an option you can download new items by using onAppear modifier on the last cell(it is a static button in this example)

var body: some View {
        List {
            ForEach(range) { number in
                Text("\(self.textfieldText) \(number)")
            }
            Button(action: loadMore) {
                Text("")
                }
                .onAppear {
                    DispatchQueue.global(qos: .background).asyncAfter(deadline: DispatchTime(uptimeNanoseconds: 10)) {
                        self.loadMore()
                    }
            }
        }
    }

请记住,dispatch 是必要的,因为如果没有它,您将收到一条错误消息,提示正在更新表视图时更新表视图.可能您可以使用另一种异步方式来更新数据

Keep in mind, that dispatch is necessary, because without it you will have an error saying "Updating table view while table view is updating). Possible you may using another async way to update the data

这篇关于使用 SwiftUI 加载更多功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆