0

I'm currently developing an application using SwiftUI and trying to refresh data using pull action.

When I implement the function in List it works, but if I use that in NavigationView the function doesn't work...

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

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

Is there any way to use the function in NavigationView?


Here are the codes:

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: Version 12.3

iOS: 14.0

Tio
  • 944
  • 3
  • 15
  • 35

1 Answers1

2

I haven't solved your problem, but you should use this library SwiftUIRefresh

Ho Si Tuan
  • 520
  • 3
  • 13
  • 1
    Thank you for your support, it's an easy way and helpful! in my case, I used it with some solution(https://github.com/siteline/SwiftUIRefresh/issues/15) – Tio May 10 '21 at 02:27