我試圖在SwiftUI中包裝UIScrollView以獲得一些額外的功能。我想訪問UIScrollView的contentOffset屬性,并將其分配給SwiftUI的一些屬性(Published 或系結),但SwiftUI(我的ContentView)沒有檢測到任何屬性變化。你能幫我解決這個問題嗎?
這是我的UIScrollView
import SwiftUI
import UIKit
struct MyScrollView<Content: View>。UIViewRepresentable {
var viewModel: ViewModel var viewModel.
var content: () -> Content
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UIScrollViewDelegate {
var parent: MyScrollView
init(_ parent: MyScrollView) {
self.parent = parent
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
parent.viewModel.scrollviewContentOffset = scrollView.contentOffset.y
}
}
func makeUIView(context: Context) -> UIScrollView {
let scrollView = UIScrollView()
scrollView.delegate = context.coordinator
scrollView.isScrollEnabled = true
let child = UIHostingController(rootView: content()
scrollView.addSubview(child.view)
let newSize = child.view.sizeThatFits(CGSize(width: UIScreen.screenWidth, height: UIScreen.screenHeight))
child.view.frame = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
scrollView.contentSize = newSize
return scrollView
}
func updateUIView(_ uiView: UIScrollView, context: Context) {
//
}
typealias UIViewType = UIScrollView
}
而這是我的ContentView
import SwiftUI
class ViewModel。ObservableObject {
var scrollviewContentOffset = CGFloat.零
}
struct ContentView: View {
private var viewModel = ViewModel()
var body。some View {
MyScrollView(viewModel: viewModel) {
ForEach(0...< 100) { i in
Text("(i)")
.offset(y: viewModel.scrollviewContentOffset / CGFloat(i 1)
}
}
}
}
CodePudding
在創建你的MyScrollView時,你只捕獲了初始的內容,而沒有在視圖模型改變時更新它。
您需要在updateUIView內設定更新的content。例如,你可以將hostingController存盤在Coordinator里面:
struct MyScrollView<Content: View>。UIViewRepresentable {
@StateObject var viewModel: ViewModel
@ViewBuilder var content: () -> Content
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, UIScrollViewDelegate {
let parent: MyScrollView
var hostingController: UIHostingController<Content> !
init(_ parent: MyScrollView) {
self.parent = parent
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
parent.viewModel.scrollviewContentOffset = scrollView.contentOffset.y
}
}
func makeUIView(context: Context) -> UIScrollView {
let scrollView = UIScrollView()
scrollView.delegate = context.coordinator
scrollView.isScrollEnabled = true
let child = UIHostingController(rootView: content()
context.coordinator.hostingController = child
scrollView.addSubview(child.view)
let newSize = child.view.sizeThatFits(CGSize(width: UIScreen.main.bound.width, height: UIScreen.main.bounds.height))
child.view.frame = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
scrollView.contentSize = newSize
return scrollView
}
func updateUIView(_ uiView: UIScrollView, context: Context) {
context.coordinator.hostingController.rootView = content()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/323148.html
標籤:
