我使用了List个简单的数据列表.我想添加下拉刷新功能,但我不确定哪种方法是最好的.

下拉刷新视图只有在用户try 从第一个索引中下拉时才可见,就像我们在UITableViewUIKit中的UIRefreshControl中所做的一样

下面是在SwiftUI中列出数据的简单代码.

struct CategoryHome: View {
    var categories: [String: [Landmark]] {
        .init(
            grouping: landmarkData,
            by: { $0.category.rawValue }
        )
    }

    var body: some View {
        NavigationView {
            List {
                ForEach(categories.keys.sorted().identified(by: \.self)) { key in
                    Text(key)
                }
            }
            .navigationBarTitle(Text("Featured"))
        }
    }
}

推荐答案

我正在玩的一款应用程序也需要同样的功能,而且SwiftUI API目前似乎不包括ScrollView秒的刷新控制功能.

随着时间的推移,API将开发并纠正这类情况,但SwiftUI中缺少功能的一般回退将始终是实现一个实现UIViewRepresentable的 struct .这里是一个快速和肮脏的UIScrollView与刷新控制.

struct LegacyScrollView : UIViewRepresentable {
    // any data state, if needed

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIView(context: Context) -> UIScrollView {
        let control = UIScrollView()
        control.refreshControl = UIRefreshControl()
        control.refreshControl?.addTarget(context.coordinator, action:
            #selector(Coordinator.handleRefreshControl),
                                          for: .valueChanged)

        // Simply to give some content to see in the app
        let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
        label.text = "Scroll View Content"
        control.addSubview(label)

        return control
    }


    func updateUIView(_ uiView: UIScrollView, context: Context) {
        // code to update scroll view from view state, if needed
    }

    class Coordinator: NSObject {
        var control: LegacyScrollView

        init(_ control: LegacyScrollView) {
            self.control = control
        }

        @objc func handleRefreshControl(sender: UIRefreshControl) {
            // handle the refresh event

            sender.endRefreshing()
        }
    }
}

但是,当然,在滚动视图中使用任何SwiftUI组件时,如果不将其包装在UIHostingController中,并将其放入makeUIView中,而不是将其放入LegacyScrollView() { // views here }中,则是不可能的.

Swift相关问答推荐

是否有一个Kotlin等价的Swift s @ AddendableReport注释'

如何使用快速宏用来自函数的关联值来初始化枚举?

如何防止自动状态恢复,如果应用程序被启动打开特定的文档?

有没有一种方法可以迭代可编码的代码(例如,JSON解析中的每一项)?

如何设置两个不同的视图模型以在我的SwiftUI应用程序中使用相同的数据源?

SwiftData/PersistentModel.swft:540:致命错误:不支持的关系密钥路径ReferenceWritableKeyPath

如何使用Duration.TimeFormatStyle以h m s格式快速格式化时间

如何使用模型在 SwiftUI 的列表中进行搜索

ClosedRange.Swift 中 Int 的索引?

从文字创建数组时的 Swift 宏

使用 Async-Await 和 Vapor-Fluent 创建 CRUD 函数 - Swift 5.6

并发执行代码中捕获的 var 的变异

为 SwiftUI 中的属性提供默认值

如何在 Swift 中使用子定义覆盖父类扩展

Swift 全局函数列表

Swift - 给定一个像 30 的 Int 如何将范围数乘以 7?

为什么 swift 中的类没有存储类型属性?

Swift 协议只能设置?

自动布局:获取 UIImageView 高度以正确计算单元格高度

如何快速格式化用户显示(社交网络等)的时间间隔?