如何在导航视图中补充 UIScrollView?

时间:2021-05-09 16:19:36

标签: swiftui swiftui-navigationview

我目前正在使用 SwiftUI 开发应用程序并尝试使用拉取操作刷新数据。

当我在 List 中实现该函数时,它可以工作,但如果我在 NavigationView 中使用该函数,则该函数不起作用...

// ---OK↓---
RefreshScrollViewTest(refreshControl: self.$refreshControl)

// ---NG↓---
NavigationView{
    RefreshScrollViewTest(refreshControl: self.$refreshControl)
}

有没有办法使用NavigationView中的函数?


代码如下:

import SwiftUI

struct NavigationRefreshTest: View {

    @State var refreshControl = UIRefreshControl()

    var body: some View {
        //        NavigationView{
        RefreshScrollViewTest(refreshControl: self.$refreshControl)
        //        }
    }
}


struct RefreshListTest:View {

    @Binding var refreshControl:UIRefreshControl

    var body: some View{
            List{
                Text("test1")
                Text("test2")
                Text("test3")
            }
        .onAppear{
            NotificationCenter.default.addObserver(forName: NSNotification.Name("Update"), object: nil, queue: .main){ (_) in
                DispatchQueue.main.asyncAfter(deadline: .now() + 1){
                    print("update...")
                }
            }
        }
    }
}


struct RefreshScrollViewTest:UIViewRepresentable {

    func makeCoordinator() ->Coodinator {
        return RefreshScrollViewTest.Coodinator()
    }

    @Binding var refreshControl:UIRefreshControl

    func makeUIView(context: Context) -> UIScrollView {
        let view = UIScrollView()

        self.refreshControl.attributedTitle = NSAttributedString(string: "Loding")
        self.refreshControl.addTarget(context.coordinator, action: #selector(context.coordinator.update), for: .valueChanged)

        view.showsVerticalScrollIndicator = false
        view.refreshControl = self.refreshControl
        view.contentSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)

        let child = UIHostingController(rootView: RefreshListTest(refreshControl: self.$refreshControl))

        child.view.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width,
                                  height: UIScreen.main.bounds.height)
        view.addSubview(child.view)

        return view
    }

    func updateUIView(_ uiView: UIScrollView, context: Context) {
    }

    class Coodinator:NSObject{
        @objc func update(){
            NotificationCenter.default.post(name: NSNotification.Name("Update"), object: nil)
        }
    }
}

Xcode:12.3 版

iOS:14.0

1 个答案:

答案 0 :(得分:2)

我还没有解决你的问题,但你应该使用这个库SwiftUIRefresh