将UIScrollView与@ViewBuilder集成,但内容中的子视图不更新

Not*_* Mi 5 uiscrollview swift swiftui

我使用 UIRepresentable 将 UIScrollView 与 SwiftUI 集成,并且在显示上工作正常。我使用 @ViewBuilder 允许人们将他们的自定义内容插入到我的自定义滚动视图中,但是我发现 @State 变量在我的自定义滚动视图中的自定义内容中不起作用。我对这个问题很困惑。有人可以帮助我吗?

我发现滚动时会调用 updateUIView ,但我不知道为什么 @ViewBuilder 中的文本不更新,以及如何使其更新。

演示项目:

import SwiftUI

struct ContentView: View {
    
    @State var speed: CGFloat = 0
    
    @State var offset: CGFloat = 0
    
    var body: some View {
        
        VStack {
            
            // This Text works
            Text("Speed: \(speed), Offset: \(offset)")
                    
            UIScrollViewControl(speed: $speed, offset: $offset, contentWidth: UIScreen.main.bounds.width, contentHeight: UIScreen.main.bounds.height) {
                
                // This Text never updates
                Text("Speed: \(speed), Offset: \(offset)")
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

UIScrollViewControl.swift

struct UIScrollViewControl<Content: View>: UIViewRepresentable {
    
    @Binding var speed: CGFloat
    
    @Binding var offset: CGFloat
    
    var contentHeight: CGFloat
    
    var contentWidth: CGFloat
    
    let content: Content
    
    init(speed: Binding<CGFloat>, offset: Binding<CGFloat>, contentWidth: CGFloat, contentHeight: CGFloat, @ViewBuilder content: () -> Content) {
        self._speed = speed
        self._offset = offset
        self.contentWidth = contentWidth
        self.contentHeight = contentHeight
        self.content = content()
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(parent1: self)
    }
    
    func makeUIView(context: Context) -> UIScrollView {
        let view = UIScrollView()
        view.contentSize = CGSize(width: 1.0, height: contentHeight)
        view.showsHorizontalScrollIndicator = false
        view.showsVerticalScrollIndicator = false
        view.delegate = context.coordinator
        
        let view1 = UIHostingController(rootView: content)
        view1.view.frame = CGRect(x: 0, y: 0, width: contentWidth, height: contentHeight)
        view1.view.backgroundColor = .clear
        view.addSubview(view1.view)
        return view
    }
    
    func updateUIView(_ uiView: UIScrollView, context: Context) {
    }
    
    class Coordinator: NSObject, UIScrollViewDelegate {
        
        var parent: UIScrollViewControl
        
        init(parent1: UIScrollViewControl) {
            parent = parent1
        }
        
        func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
            parent.speed = 0
        }
        
        func scrollViewDidScroll(_ scrollView: UIScrollView) {
            parent.speed = scrollView.contentOffset.y - parent.offset
            parent.offset = scrollView.contentOffset.y
        }
    }
}
Run Code Online (Sandbox Code Playgroud)