vue 列表带分页_如何在SwiftUI中创建带有分页的列表

vue 列表带分页

Hi!, I’m writing this article because I wanted to share my experience with a problem in my current job using SwiftUI, and how I found a solution for it. You will learn (like title mention) how to build a list that supports pagination in SwiftUI.

嗨,我写这篇文章是因为我想分享我在使用SwiftUI的当前工作中遇到问题的经验,以及如何找到解决方案。 您将学习(如标题提及)如何在SwiftUI中构建支持分页的列表。

分页 (Pagination)

If you work with iOS (or any mobile platform), in many cases, you will have to build a list of “something” reading data from an API. This sounds trivial (and it is in some way) until you realize that your app can’t handle thousands of records at the same time, getting timeout errors or leaving the user stuck waiting a long time to finally see the information… That is not a good user experience at all.

如果您使用iOS(或任何移动平台),在许多情况下,您将必须构建一个从API读取数据的“内容”列表。 在您意识到您的应用程序无法同时处理数千条记录,出现超时错误或使用户停留很长时间才能最终看到信息之前,这听起来是微不足道的(从某种程度上来说)。良好的用户体验。

waiting for loading the list
Will someday the list finishes loading… right?
清单是否有一天会完成加载...对吗?

To avoid this, there is a technique well-known called “pagination”, which is basically loading data per chunks, and not all in one single call. This helps the server to respond immediately and your app loads the result in the screen way faster than using the previous approach.

为了避免这种情况,有一种众所周知的“ 分页 ”技术,它基本上是按块加载数据,而不是一次调用就全部加载。 与以前的方法相比,这有助于服务器立即做出响应,并且您的应用程序可以以屏幕方式更快地加载结果。

那么SwiftUI呢? (What about SwiftUI?)

SwiftUI is a brand-new framework for building UI in a declarative way released in the past WWDC 2019. If you are new with SwiftUI, I recommend you to watch this video first:

SwiftUI是一个全新的框架,用于在过去的WWDC 2019中发布以声明式方式构建UI。如果您是SwiftUI的新手,我建议您首先观看以下视频:

SwiftUI is really powerful in terms of expressiveness and clarity of how you build your views with less code than UIKit, however, one of the greatest limitation at this time is the lack of good support for documentation and a vast set of tools to use, one of them is pagination. Yeah, there’s no native support for pagination right now, and if you’re all planning to create a production app with SwiftUI anyway, you won’t find a solution for it… or maybe yes?

SwiftUI在表达性和清晰度方面比UIKit少得多,因此确实具有强大的功能,但是,当前最大的限制之一是缺乏对文档的良好支持以及大量使用的工具,其中之一其中是分页。 是的,目前还没有对分页的本机支持,并且如果您都打算使用SwiftUI创建生产应用程序,那么您将找不到解决方案……或者是吗?

Image for post

在SwiftUI中使用分页实现列表 (Implementing List with pagination in SwiftUI)

We need the following properties in order to print the information in our paginated list:

我们需要以下属性才能在分页列表中打印信息:

  • Items to be rendered.

    要渲染的项目。
  • The view that will host each item value (cell).

    将托管每个项目值(单元格)的视图。
  • A method to execute the retrieving of data when pagination is triggered.

    触发分页时执行数据检索的方法。
  • A @State to identify when the list is loading.

    标识列表加载时间的@ State

  • An optional offset to decide when the list should be reloaded with more data.

    一个可选的offset用于确定何时应在列表中重新加载更多数据。

With all these “ingredients”, we can now set up our list with pagination.

有了所有这些“成分”,我们现在可以分页设置列表。

Image for post
Let’s cook our list! (Photo by Katie Smith on Unsplash)
让我们做饭吧! ( 凯蒂·史密斯 ( Katie Smith)Unsplash拍摄的照片)

主要结构 (The main struct)

Our List, of course, will be a struct that inherits from View protocol. We have to declare two generic parameters: Item which adopts Identifiable protocol and Content that represent the View container for each item value.

当然,我们的列表将是从View协议继承的结构。 我们必须声明两个通用参数:采用可Identifiable协议的Item和代表每个项目值的View容器的Content

The rest of the properties are:

其余属性为:

初始化器 (Initializer)

Our initializer will take three parameters, the list of items, the pagination (escaping) method, and the content closure marked with @ViewBuilder attribute in order to let Swift know that we can create SwiftUI content within that closure.

我们的初始化程序将使用三个参数:项目列表,分页( escaping )方法和标有@ ViewBuilder属性的内容闭包,以便让Swift知道我们可以在该闭包中创建SwiftUI内容。

分页助手 (Helpers for pagination)

The actual magic happens in three methods:

实际的魔术发生在三种方法中:

  • One method to identify if we have reached the end of the list

    一种确定我们是否已到达列表末尾的方法

  • Another method to check if our offset has been reached

    另一种检查我们的偏移量是否达到的方法

  • Finally, a method that will trigger the loading animation and let us know when the pagination method finished its work.

    最后,一种方法将触发加载动画,并在分页方法完成工作时通知我们。

Note: Thanks to RandomAccessCollection protocol for arrays, checking count property is guaranted to be O(1), so performance is not an issue this case! ☺️

注意 :由于使用了用于数组的RandomAccessCollection协议,因此保证将count属性保证为O(1),因此在这种情况下性能不是问题! ☺️

我的身体已经准备好💪! (My body is ready 💪!)

Now it’s time to set up the body in our view. This would be the result of combining all the code above:

现在是时候在我们看来建立机构了。 这将是结合以上所有代码的结果:

Couple of things to explain here:

这里要解释的几件事:

  1. We iterate through indices, not the actual item values, this helps us to identify the exact index position when we need it.

    我们遍历索引,而不是实际的项目值,这有助于我们在需要时识别确切的索引位置。

Note: I decided to use ForEach instead of List because it’s more flexible especially if we want to add list with sections, however, you can replace it to use List directly.

注意:我决定使用ForEach而不是List因为它更加灵活,尤其是当我们要添加带有部分的列表时,但是,您可以替换它以直接使用List

2. Display the actual item in the cell the caller was invoked.

2.在调用者的单元格中显示实际项目。

3. Check the state if it’s time to display a loading message (or animation like the example) and if we are positioned at the end of the list.

3.检查状态是否需要显示加载消息(或类似示例的动画)以及我们是否位于列表的末尾。

4. In this case, we are displaying a custom view that is actually a ViewRepresentable protocol that displays an activity indicator.

4.在这种情况下,我们将显示一个自定义视图,该视图实际上是一个显示活动指示器的ViewRepresentable协议。

5. The whole content is wrapped in a VStack for convenience, and tracking each index to trigger the pagination method when conditions are true.

5.为了方便起见,将整个内容包装在VStack中,并在条件为真时跟踪每个索引以触发分页方法。

准备行动 (Ready for action)

It’s time to test our new List with pagination. To do that, we going to create a simulated API call through a ViewModel and a Custom View. Let’s start by creating our ViewModel what will call an “async” method to retrieve the information:

现在该使用分页功能测试我们的新List了。 为此,我们将通过ViewModel和Custom View创建一个模拟的API调用。 让我们从创建ViewModel开始,该模型将称为“异步”方法以检索信息:

  1. We create a ViewModel that conforms ObservableObject in order to Publish changes to Subscribers of this object, this is possible thanks to new Combine framework with works very well with SwiftUI.

    我们创建了一个符合ObservableObject的ViewModel,以便将更改Publish到该对象的Subscribers ,这要归功于新的Combine框架,它与SwiftUI的配合非常好。

  2. Declare the array that will store the actual information and decorated with @Published property to communicate subscribers that new data is required to be rendered in the view.

    声明将存储实际信息并用@ Published属性修饰的数组,以通知订阅者需要在视图中呈现新数据。

  3. Declare the values that will control our pagination:

    声明将控制我们的分页的值:
  • The items to be loaded per batch (itemsPerPage)

    每批要加载的项目( itemsPerPage )

  • The current start and end (stop) indices of the (chunked) data.

    (分块)数据的当前start和结束( stop )索引。

  • For this example, we also set a maxData value to demonstrate when we reach the last element possible.

    在此示例中,我们还设置了一个maxData值来演示何时到达最后一个元素。

4. The main method that will increase the pagination indices and retrieve the data from “a server”.

4.增加分页索引并从“服务器”检索数据的主要方法。

5. Finally, since in our demo items is an Array of Ints and items parameter from our ListPagination requires that each item conforms Identifiable , we create an extension to adopt it for allInt values.

5.最后,因为在我们的演示items是一个ArrayInts和项目参数从我们ListPagination要求每个项目符合Identifiable ,我们创建的扩展,通过它的所有Int值。

最终测试 (The Final Test)

Now let’s see how we going to test and run our list with pagination. It’s very simple:

现在,让我们看看如何使用分页测试和运行列表。 很简单:

  1. Create a subscriber using @ObservedObject property for our viewModel.

    使用@ ObservedObject属性为我们的viewModel创建一个订阅者。

  2. Call ListPagination with items to be displayed, a custom offset, and the method that will be executed when pagination is activated.

    调用ListPagination其中包含要显示的项目,自定义偏移量以及激活分页时将执行的方法。

  3. Display a custom cell, in this case, it’s a simple Text view.

    显示自定义单元格,在这种情况下,这是一个简单的Text视图。

  4. Call our method to get the first n values displayed on our list once the view appears on the screen.

    当视图出现在屏幕上时,调用我们的方法以使列表中显示前n个值。

See the demo in action:

观看实际的演示:

Image for post
Horray! 🙌
霍雷! 🙌

If you want to check the full source code and run the demo, follow the link below:

如果要检查完整的源代码并运行演示,请单击下面的链接:

We made it!. Is it not awesome? 😄. I hope this article has been of great help to you.

我们做到了! 难道不是吗? 😄。 希望本文对您有很大帮助。

By the way, if you found a better solution than this one, please let me know in the comments or through my twitter account @pitt500. I’m glad to hear great your ideas!

顺便说一句,如果您找到了比该解决方案更好的解决方案,请在评论中或通过我的Twitter帐户@ pitt500 告诉我 我很高兴听到您的好主意!

That’s it for now. Thanks for reading and see you in the next one!

现在就这样。 感谢您的阅读,下一个再见!

翻译自: https://medium.com/@pedrorojas.dev/how-to-create-a-list-with-pagination-in-swiftui-215244840b48

vue 列表带分页

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值