How to implement a lazy-loading ScrollView with UIViewRepresentable with SwiftUI?
Asked Answered
S

0

7

I'm trying to implement a lazy-loading MyLazyHStack view using UIViewRepresentable, but it's not loading the elements lazily. I'm using LazyHStack in the content of MyLazyHStack, but all the elements are loading at once instead of loading lazily as needed. Here's a minimal example of my code. Can someone help me figure out what I'm doing wrong?

struct MyLazyHStack<Content: View>: UIViewRepresentable {
    var content: Content
    
    func makeUIView(context: Context) -> UIView {
        let scrollView = UIScrollView()
        scrollView.isPagingEnabled = true
        
        let hostingController = UIHostingController(rootView: content)
        hostingController.view.translatesAutoresizingMaskIntoConstraints = false
        
        scrollView.addSubview(hostingController.view)
        
        NSLayoutConstraint.activate([
            hostingController.view.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            hostingController.view.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
            hostingController.view.topAnchor.constraint(equalTo: scrollView.topAnchor),
            hostingController.view.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
            hostingController.view.heightAnchor.constraint(equalTo: scrollView.heightAnchor)
        ])
        
        return scrollView
    }
    
    func updateUIView(_ uiView: UIView, context: Context) {}
}

struct ContentView: View {
    var body: some View {
        MyLazyHStack {
            LazyHStack {
                ForEach(1..<100) { index in
                    Text("Element \(index)")
                }
            }
        }
    }
}
Secure answered 27/3, 2023 at 20:25 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.