3

I am trying to develop my first IOS app in SwiftUI and I want to have a pull down to refresh List. I already know that at the moment Apple hasn't implemented it but I found the following solution here on stackoverflow (Pull down to refresh data in SwiftUI) and I am implemented the solution from the first answer. And this works fine.

But now I want to have a SwiftUI View in this refreshable View. The solution says I have to:

wrapping them in a UIHostingController and dropping them in makeUIView

And here is my problem. What did I have to do exactly? I tried the following but it isn't working.

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)*/

    let parent = UIViewController()
    let child = UIHostingController(rootView: RecipeList())
    child.view.translatesAutoresizingMaskIntoConstraints = false
    child.view.frame = parent.view.bounds
    // First, add the view of the child to the view of the parent
    parent.view.addSubview(child.view)
    // Then, add the child to the parent
    parent.addChild(child)

    return control
}

Has anyone an idea what I am doing wrong and can tell me what I have to change?

Thanks and best regards

Henrik

  • You haven’t added any of your controls to the UIScrollView `control`, so none of them are going to appear. You should just be able to do `control.addChild(child)` and remove the `parent` altogether. Make that change and see if it works. If not, it would be helpful to know more detail as to how it isn’t working. – Evan Deaubl Nov 03 '19 at 21:47
  • Thanks for your response. But when I try this I only get the following error: `Value of type 'UIScrollView' has no member 'addChild'`. I Am using exactly our code from the other page and at the moment I try to add a simple text: `let child = UIHostingController(rootView: Text("Hello"))`. This I added in the `makeUIView`function. Everything else is only copied from the other post – Henrik Geiger Nov 04 '19 at 15:38

1 Answers1

0

iOS 15+

struct ContentView: View {
    var body: some View {
        NavigationView {
            if #available(iOS 15.0, *) {
                List(1..<100) { row in
                    Text("Row \(row)")
                }
                .refreshable {
                    print("write your pull to refresh logic here")
                }
            } else {
                // Fallback on earlier versions
            }
        }
    }
}
YodagamaHeshan
  • 4,996
  • 2
  • 26
  • 36