我正在开发一个混合使用 UIKit 和 SwiftUI 的项目。我目前有一个 ZStack,我在其中保存了我的 SwiftUI 内容,我需要在该内容之上显示一个 UIViewController。所以我的 ZStack 中的最后一项是 UIViewControllerRepresentable。 IE:
ZStack {
...
SwiftUIContent
...
MyUIViewControllerRepresentative()
}
我覆盖的 UIViewControllerRepresentative 是其他 UIViewControllers 的容器。那些 subview Controller 并不总是需要占据全屏,因此 UIViewControllerRepresentative 具有透明背景,因此用户可以与后面的 SwiftUI 内容进行交互。
我面临的问题是 UIViewControllerRepresentative 阻止所有触摸事件到达 SwiftUI 内容。
我试过像这样覆盖 UIViewControllers View HitTest :
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
// return nil if the touch event should propagate to the SwiftUI content
}
我还尝试通过以下方式完全删除 View Controller View 上的触摸事件:
view.isUserInteractionEnabled = false
即使这样也行不通。
任何帮助将非常感激。
最佳答案
解决方案:
我设法想出了一个可行的解决方案。
我没有将 UIViewControllerRepresentable 放在 ZStack 中,而是创建了一个自定义 ViewModifier,它将内容值传递给 UIViewControllerRepresentable。然后将该内容嵌入到我的 UIViewController 中,方法是将其包装在 UIHostingController 中并将其添加为 subview Controller 。
ZStack {
... SwiftUI content ...
}.modifier(MyUIViewControllerRepresentative)
关于ios - SwiftUI 将触摸事件从 UIViewControllerRepresentable 传递给 View 后面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59129988/